Welcome to TiddlyWiki created by Jeremy Ruston, Copyright © 2007 UnaMesa Association
|''Type:''|file|
|''URL:''|http://tiddlyvault.tiddlyspot.com/|
|''Workspace:''|(default)|
This tiddler was automatically created to record the details of this server
/***
|''Name:''|ASCIIsvgPlugin|
|''Description:''|Mathematical vector graphics based on [[ASCIIsvg|http://www1.chapman.edu/~jipsen/asciisvg.html]]|
|''Version:''|1.0.0|
|''Date:''|Sep 12, 2007|
|''Source:''|http://www.math.ist.utl.pt/~psoares/addons.html|
|''Documentation:''|[[ASCIIsvgPlugin Documentation|ASCIIsvgPluginDoc]]|
|''Author:''|Paulo Soares|
|''License:''|[[Creative Commons Attribution-Share Alike 3.0 License|http://creativecommons.org/licenses/by-sa/3.0/]]|
|''~CoreVersion:''|2.1.0|
***/
//{{{
Story.prototype.ASCIIsvgRefreshTiddler = Story.prototype.refreshTiddler;
Story.prototype.refreshTiddler = function(title,minorUpdate) {
setTimeout('drawPictures()',100);
return(this.ASCIIsvgRefreshTiddler(title,minorUpdate));
}
config.shadowTiddlers.ASCIIsvgPluginDoc="The documentation is available [[here.|http://www.math.ist.utl.pt/~psoares/addons.html#ASCIIsvgPluginDoc]]";
//}}}
!Description
This plugin is a wrapper for a modified version of Peter Jipsen's [[ASCIIsvg|http://www1.chapman.edu/~jipsen/asciisvg.html]]. The main changes are:
#mouseover effects over the figures were removed (too much clumsy code to so little results...)
#a unique id for each figure is mandatory
#small changes in some functions' names (for improved coherence)
Most of the syntax was preserved so, to be able to draw beautiful SVG pictures in your ~TiddlyWiki you should take a look at the [[ASCIIsvg|http://www1.chapman.edu/~jipsen/asciisvg.html]] site.
The plugin is known to do a good job with Mozilla Firefox 2.0 and Opera 9.23. I'm not sure about the awful Internet Explorer (with the Adobe SVG plugin).
!Installation
This is not a self-contained plugin. To install it, download the modified ~ASCIIsvg code [[here|http://www.math.ist.utl.pt/~psoares/TWASCIIsvg.js]] and this other [[one|http://www.math.ist.utl.pt/~psoares/d.svg]], and put them next to your ~TiddlyWiki file. Next, add the following line to the MarkupPreHead tiddler:
{{{
<script type="text/javascript" src="TWASCIIsvg.js"></script>
}}}
Finally, copy the ASCIIsvgPlugin tiddler to your ~TiddlyWiki, give it the //systemConfig// tag, save and reload.
!Credits
A final word of appreciation for Peter Jipsen's fine work on promoting beautiful math in the web.
<<slideShow noClicks forceRefresh>>
-s-
!
In questa presentazione, deriviamo la formula per la somma di una serie geometrica partendo dal presupposto che il paradosso di Zeno sia falso e che Achille riesca a catturare la tartaruga.
{{Comment{
@@Premi F11 per allargare a tutto schermo ed utilizza Ctrl++ Ctrl+- (or Ctrl+rotella) per cambiare la dimensione dei caratteri.@@}}}
-s-
!Il Paradosso di Zeno – ca. 450 a.C.
Una tartaruga sfida Achille in una corsa.
La tartaruga sostiene di poter vincere se viene fatta partire in vantaggio,
dato che Achille non può riuscire a raggiungerla.
-s-
!Achille e la tartaruga
Se la tartaruga parte con un vantaggio iniziale pari ad $a$ metri, Achille deve cominciare a correre per i primi $a$ metri.
Nel frattempo la tartaruga percorre circa $\frac{a}{10}$ metri.
Quindi Achille deve correre per $\frac{a}{10}$ metri mentre la tartaruga percorre di nuovo circa $\frac{a}{100}$ metri, e così via.
Rimane sempre una distanza tra Achille e la tartaruga.
-s-
!Achille riesce a raggiungere la tartaruga?
Se la velocità di Achille e' $v$ m/s, allora la tartaruga, che e' piu' lenta, avrà una velocità pari a $qv$ m/s, per $0<q<1$.
|! Achille corre |! La tartaruga corre |
| $a$ metri | $qa$ metri |
| $qa$ metri | $q²a$ metri |
| $q²a$ metri | $q³a$ metri |
-s-
!Quanto deve correre Achille?
|! Round |! Distanza |! Achille corre |! La tartaruga corre |
| 1 | $a$ metri | $a$ metri | $qa$ metri |
| 2 | $qa$ metri | $qa$ metri | $q²a$ metri |
| 3 | $q²a$ metri | $q²a$ metri | $q³a$ metri |
Risposta: Achille deve correre $a+aq+aq²+aq³+…$ metri per raggiungere la tartaruga.
-s-
!Quando riuscirà Achille a raggiungere la tartaruga?
Achille avrà raggiunto la tartaruga quando avrà corso $a$ metri oltre la tartaruga.
Date le velocità $v$ m/s per Achille, e $qv$ m/s, dove $0<q<1$, per la tartaruga, si ottiene che Achille impiega un tempo $t$ per raggiungere la tartaruga tale che:
$$vt=a+qvt$$
Quindi, Achille riuscirà a raggiungere la tartaruga in $t=\frac{a}{v(1-q)}$ secondi.
-s-
!Dove raggiungerà Achille la tartaruga?
Sappiamo che Achille impiega $t=\frac{a}{v(1-q)}$ secondi per raggiungere la tartaruga.
Achille quindi percorre metri:
$$vt=\frac{a}{v(1-q)}v=\frac{a}{1-q}$$
per raggiungere la tartaruga.
-s-
!Serie Geometrica
Paradosso di Zeno: Achille deve correre $a+aq+aq²+aq³+…$ metri per raggiungere la tartaruga.
Formula per la somma di una serie geometrica:
$$a+aq+aq²+aq³+…= \sum_{k=0}^{\infty}aq^k=\frac{a}{1-q}$$
per $|q|<1$.
-s-
!
[img[Achille cattura la tartaruga|http://farm3.static.flickr.com/2194/2420999602_92b160cd3d_m.jpg]]
Zeno spiega così il paradosso.
Se la tartaruga parte con un vantaggio iniziale pari ad $a$ metri, Achille deve cominciare a correre per i primi $a$ metri. Nel frattempo la tartaruga percorre circa $\frac{a}{10}$ metri.
Quindi Achille deve correre per $\frac{a}{10}$ metri mentre la tartaruga percorre di nuovo circa $\frac{a}{100}$ metri, e così via.
Zeno quindi conclude che rimane sempre una distanza tra Achille e la tartaruga. La domanda é: [[Achille riesce a raggiungere la tartaruga?]]
Ora si supponga che la velocità di Achille sia $v$ m/s, mentre quella della tartaruga $qv$ m/s, per $0<q<1$. Chiaramente, nel caso di una tartaruga, $q$ deve essere più vicino a $0$ che ad $1$ (altrimenti avremmo una tartaruga veloce quanto Achille). Siccome il rapporto tra la velocita di Achille e quella della tartaruga é $q$, se Achille corre $a$ metri, la tartaruga ne corre $qa$ ($v:qv=a:qa$). Seguendo le linee del ragionamento di Zeno, si ha:
|! Achille corre |! La tartaruga corre|
| $a$ metri | $qa$ metri|
| $qa$ metri | $q²a$ metri|
| $q²a$ metri | $q³a$ metri|
Proviamo a vedere [[quanto deve correre Achille per raggiungere la tartaruga|Quanto deve correre Achille?]].
/***
|''Name:''|BibTeXPlugin|
|''Description:''|Very incomplete BibTeX implementation to work with bibliographic references|
|''Version:''|1.0.0|
|''Date:''|Sep 12, 2007|
|''Source:''|http://www.math.ist.utl.pt/~psoares/addons.html|
|''Documentation:''|[[BibTeXPlugin Documentation|BibTeXPluginDoc]]|
|''Author:''|Paulo Soares|
|''License:''|[[Creative Commons Attribution-Share Alike 3.0 License|http://creativecommons.org/licenses/by-sa/3.0/]]|
|''~CoreVersion:''|2.1.0|
***/
//{{{
config.macros.cite = {noReference: "(??)", biblioTiddler: ""};
config.macros.bibliography = {title: "!References"};
config.macros.bibliography.handler=function(place,macroName,params,wikifier,paramString,tiddler) {
if(params.length==0) return;
var title = params[0];
var showAll = getParam(paramString.parseParams("list",null,true),"showAll",false);
var entry, entryText, start, bib, prefix;
var entries = new Array();
if(title!="") wikify(config.macros.bibliography.title, place);
if(showAll) {
if(store.tiddlerExists(title)) entryText = extractAllEntries(title);
for(i=0; i<entryText.length; i++) {
bib = processEntry(entryText[i], true);
entries.push(bib[1]);
}
} else {
var text = store.getTiddlerText(tiddler.title);
var idx = -1;
while(true) {
idx = text.indexOf("<<cite",idx);
if(idx==-1) break;
start = text.indexOf(" ",idx)+1;
idx = Math.min(text.indexOf(">>",start),text.indexOf(" ",start));
entry = text.substring(start,idx);
if(store.tiddlerExists(title)) entryText = extractEntry(title, entry);
idx++;
if(entryText != null) {
bib = processEntry(entryText, true);
entries.push(bib[1]);
}
}
}
entries.sort();
for (var i=0; i < entries.length; i++) {
prefix = (i>0) ? "\n\n" : "";
wikify(prefix + entries[i] , place);
}
return;
}
String.prototype.extract = extractField;
config.macros.cite.handler = function(place,macroName,params,wikifier,paramString,tiddler) {
if(params.length==0) return;
var text;
var entry = params[0];
var args = paramString.parseParams("list",null,true);
var title = getParam(args,"bibliography",undefined);
if(title) {
config.macros.cite.biblioTiddler = title;
} else {title = config.macros.cite.biblioTiddler;}
var showAll = getParam(args,"showAll",false);
if(title!="" && store.tiddlerExists(title)) text = extractEntry(title, entry);
if(text == null) {
wikify(config.macros.cite.noReference, place);
} else {
var bib = processEntry(text, showAll);
wikify(bib[0], place);
}
return;
}
function processNames(names, showAll) {
var authors = names.split(" and ");
var entry = authors[0];
var numAuthors = authors.length;
var fullEntry = entry;
if (numAuthors==2) {
entry += " and " + authors[1];
fullEntry = entry;
}
if (numAuthors>2) {
fullEntry = entry;
for (var i=1; i < numAuthors; i++) {
if (i==numAuthors-1) {fullEntry += " and "} else {fullEntry += ", "};
fullEntry += authors[i];
}
if(showAll) {entry = fullEntry;} else {entry += " et al.";}
}
return [entry,fullEntry];
}
function processEntry(text,showAll) {
var type = text.substring(text.indexOf("@")+1,text.indexOf("{"));
var authors = processNames(text.extract("author"), showAll);
var entry = authors[0] + " ("+text.extract("year")+")";
var fullEntry = authors[1] + " ("+text.extract("year")+").";
var url = text.extract("url");
var title = (url) ? "[[" + text.extract("title") + "|" + url + "]]" : text.extract("title") ;
switch(type.toLowerCase()) {
case "article":
fullEntry += " " + title + ". //" + text.extract("journal") + "// \'\'" + text.extract("volume") + "\'\', " + text.extract("pages") + ".";
break;
case "book":
fullEntry += " //" + title + "//. " + text.extract("publisher") + ".";
break;
case "inproceedings":
fullEntry += " " + title + ". In " + processNames(text.extract("editor"),true)[1] + " (Eds.), //" + text.extract("booktitle") + "//, " + text.extract("pages") + ". " + text.extract("publisher") + ".";
break;
case "incollection":
fullEntry += " " + title + ". In " + processNames(text.extract("editor"),true)[1] + " (Eds.), //" + text.extract("booktitle") + "//, " + text.extract("pages") + ". " + text.extract("publisher") + ".";
break;
case "techreport":
fullEntry += " " + title + ". Technical report, " + text.extract("institution") + ".";
break;
case "manual":
fullEntry += " //" + title + "//. " + text.extract("organization") + ".";
break;
case "unpublished":
fullEntry += " " + title + ". Unpublished.";
break;
}
return [entry, fullEntry];
}
function extractEntry(title,entry) {
var parseText = store.getTiddlerText(title);
var pos = parseText.indexOf(entry);
if(pos==-1) return null;
var previousText=parseText.substring(0,pos);
var start = previousText.lastIndexOf("@",pos);
var end = parseText.indexOf("@",pos);
var entryText = ((end==-1) ? parseText.substring(start) : parseText.substring(start,end));
return entryText;
}
function extractAllEntries(title) {
var parseText = store.getTiddlerText(title);
var start, end;
var pos = 0;
var entries = new Array();
while(true) {
start = parseText.indexOf("@",pos);
if(start==-1) break;
end = parseText.indexOf("@",start+1)+1;
if(end==0) end=parseText.length;
pos=end;
entries.push(parseText.substring(start,end));
}
return entries;
}
function extractField(fieldDescr) {
var i = this.toLowerCase().indexOf(fieldDescr);
if (i != -1) {
i += fieldDescr.length;
i += 1 + (this.substring(i,this.length)).indexOf("=");
if (i != -1) {
var contExtr = true;
var fieldDelim = ""
var fieldText = "";
var nestedPar = 0;
while (i<this.length && contExtr) {
if (fieldDelim == "") {
if (this.charAt(i) == "\"" || this.charAt(i) == "\'" || this.charAt(i)=="\`") {
fieldDelim = this.charAt(i);
} else if (this.charAt(i) == "\{") {
fieldDelim = "\}";
} else if (this.charAt(i) != " " && this.charAt(i) != "\t" && this.charAt(i) != "\n") {
fieldDelim = ",";
i--;
}
} else {
if (this.charAt(i) == "\{" && fieldDelim == "\}") {
nestedPar++;
fieldText += this.charAt(i);
} else if (this.charAt(i) == fieldDelim) {
if (nestedPar == 0) {
contExtr = false;
} else {
nestedPar--;
fieldText += this.charAt(i);
}
} else {
fieldText += this.charAt(i);
}
}
i++;
}
return fieldText;
} else {
return "";
}
} else {
return "";
}
}
config.shadowTiddlers.BibTeXPluginDoc="The documentation is available [[here.|http://www.math.ist.utl.pt/~psoares/addons.html#BibTeXPluginDoc]]";
//}}}
!Description
Very incomplete (and personal) ~BibTeX implementation to work with bibliographic references.
!Usage
First of all, you need to dump your ~BibTeX entries in a tiddler, lets call it //~MyReferences//. The first macro that this plugin provides is {{{<<cite>>}}}. As the name suggests it is used to cite a reference such as {{{<<cite Soares:07>>}}} where {{{Soares:07}}} is a ~BibTeX key for a reference. However, in your first citation you must include the name of the tiddler that contains the ~BibTeX entries like this {{{<<cite Soares:07 bibliography:MyReferences>>}}}
The {{{<<cite>>}}} macro produces a full reference if there are at most two authors, otherwise it is abbreviated. If you want to force a full reference then you can use the {{{showAll}}} parameter as in {{{<<cite Coda:97 showAll:true>>}}}.
The production of a list of cited references is done with the {{{<<bibliography>>}}} macro using the name of the tiddler that contains the ~BibTeX entries as a single parameter such as {{{<<bibliography MyReferences>>}}}. If you want to make a list of all your ~BibTeX entries then use {{{<<bibliography MyReferences showAll:true>>}}}.
//{{{
config.macros.cite = {noReference: "(??)", biblioTiddler: ""};
config.macros.bibliography = {title: "!Bibliografia"};
//}}}
{{{
@TECHREPORT{AgaGel:03,
author = {Agarwal, D. K. and Gelfand, A. E.},
title = {Slice Gibbs sampling for simulation based fitting of spatial data models},
institution = {University of Connecticut},
year = {2003},
}
@ARTICLE{Ait:91,
author = {Aitkin, M.},
title = {Posterior Bayes factors},
journal = {Journal of the Royal Statistical Society B},
year = {1991},
volume = {53},
pages = {111-142},
}
@ARTICLE{AlbChi:93,
author = {Albert, J. H. and Chib, S.},
title = {Bayesian Analysis of Binary and Polychotomous Response Data},
journal = {Journal of the American Statistical Association},
year = {1993},
volume = {88},
number = {422},
pages = {669-679},
}
@ARTICLE{BerChe:93,
author = {Berger, J. O. and Chen, M.- H.},
title = {Predicting retirement patterns: prediction for a multinomial distribution with constrained parameter space},
journal = {The Statistician},
year = {1993},
volume = {42},
pages = {427-443},
}
@ARTICLE{BesGre:93,
author = {Besag, J. and Green, P. J.},
title = {Spatial Statistics and Bayesian Computation},
journal = {Journal of the Royal Statistical Society B},
year = {1993},
volume = {55},
number = {1},
pages = {25-37},
}
@MANUAL{Coda:97,
title = {CODA - Convergence Diagnosis and Output Analysis software for Gibbs sampling output: Version 0.4},
author = {Best, N. and Cowles, M. K. and Vines, K.},
organization = {MRC Biostatistics Unit},
address = {Cambrigde},
year = {1997},
}
@TECHREPORT{Bro.R:95,
author = {Brooks, S. and Roberts, G.},
title = {Assessing convergence of Markov chain Monte Carlo algorithms},
institution = {Department of Pure Mathematics and Mathematical Statistics, University of Cambridge},
year = {1995},
number = {12},
}
@ARTICLE{Car.C:95,
author = {Carlin, B. P. and Chib, S.},
title = {Bayesian model choice via Markov chain Monte Carlo methods},
journal = {Journal of the Royal Statistical Society B},
year = {1995},
volume = {57},
pages = {473-484},
}
@ARTICLE{Cas.G:92,
author = {Casella, G. and George, E. I.},
title = {Explaining the Gibbs Sampler},
journal = {The American Statistician},
year = {1992},
volume = {46},
number = {3},
pages = {167-174},
}
@ARTICLE{CasLAvRob:01,
author = {Casella, G. and Lavine, M. and Robert, C. P.},
title = {Explaining the Perfect Sampler},
journal = {The American Statistician},
year = {2001},
volume = {55},
number = {4},
pages = {299-305},
}
@ARTICLE{ChaVan:01,
author = {Chauveau, D. and Vandekerkhove, P.},
title = {Improving convergence of the Hastings-Metropolis Algorithm with a learning proposal},
journal = {Scandinavian Journal of Statistics},
year = {2001},
volume = {29},
number = {1},
pages = {13-29},
}
@TECHREPORT{Che,
author = {Chen, M.-H.},
title = {Markov Chain Monte Carlo Sampling for Evaluating Multidimensional Integrals With Application to Bayesian Computation},
institution = {Dept of Mathematical Sciences, WPI},
}
@ARTICLE{Chi.G:95,
author = {Chib, S. and Greenberg, E.},
title = {Understanding the Metropolis-Hastings algorithm},
journal = {The American Statistician},
year = {1995},
volume = {49},
number = {4},
pages = {327-335},
}
@ARTICLE{Coo.B:95,
author = {Cook, P. and Broemeling, L.D.},
title = {Bayesian statistics using Mathematica},
journal = {The American Statistician},
year = {1995},
volume = {49},
pages = {70-76},
}
@ARTICLE{Cow.C:96,
author = {Cowles, M. K. and Carlin, B. P.},
title = {Markov chain Monte Carlo convergence diagnostics: a comparative review},
journal = {Journal of the American Statistical Association},
year = {1996},
volume = {91},
pages = {883-904},
}
@ARTICLE{DamWakWal:99,
author = {Damien, P. and Wakefield, J. and Walker, S.},
title = {Gibbs sampling for Bayesian non-conjugate and hierarchical models by using auxiliary variables},
journal = {Journal of the Royal Statistical Society B},
year = {1999},
volume = {61},
number = {Part 2},
pages = {331-344},
}
@TECHREPORT{DouGodRob,
author = {Doucet, A. and Godsill, S. J. and Robert, C. P.},
title = {Marginal Maximum A Posteriori Estimation using Markov Chain Monte Carlo},
institution = {Signal Processing Group, University of Cambridge},
}
@ARTICLE{Gel.S:90,
author = {Gelfand, A. E. and Smith, A. F. M.},
title = {Sampling-based approaches to calculating marginal densities},
journal = {Journal of the American Statistical Association},
year = {1990},
volume = {85},
number = {410},
pages = {398-409},
}
@ARTICLE{GelSmiLee:92,
author = {Gelfand, A. E. and Smith, A. F. M. and Lee, T.-M.},
title = {Bayesian Analysis of Constrained Parameter and Truncated Data Problems Using Gibbs Sampling},
journal = {Journal of the American Statistical Association},
year = {1992},
volume = {87},
number = {418},
pages = {523-532},
}
@ARTICLE{Gel.D:94,
author = {Gelfand, A. E. G. and Dey, D. K.},
title = {Bayesian model choice: asymptotics and exact calculations},
journal = {Journal of the Royal Statistical Society B},
year = {1994},
volume = {56},
pages = {501-514},
}
@ARTICLE{Gel.H.R.S:90,
author = {Gelfand, A. E. G. and Hills, S. E. and Racine-Poon, A. and Smith, A. F. M.},
title = {Illustration of Bayesian inference in normal data models using Gibbs sampling},
journal = {Journal of the American Statistical Association},
year = {1990},
volume = {85},
pages = {972-985},
}
@INCOLLECTION{GelMen:96,
author = {Gelman, A. and Meng, X.-L.},
title = {Model checking and model improvement},
booktitle = {Markov Chain Monte Carlo in Practice},
publisher = {Chapman and Hall, London},
year = {1996},
editor = {Gilks, W. R. and Richardson, S. and Spiegelhalter, D. J.},
pages = {189-202},
}
@ARTICLE{Gem.G:84,
author = {Geman, S. and Geman, D.},
title = {Stochastic relaxation, Gibbs distributions, and the Bayesian restoration of images},
journal = {IEEE Transactions on Pattern Analysis and Machine Intelligence},
year = {1984},
volume = {6},
pages = {721-741},
}
@INPROCEEDINGS{Gew:92,
author = {Geweke, J.},
title = {Evaluating the accuracy of sampling-based approaches to calculating posterior moments},
booktitle = {Bayesian Statistics 4},
year = {1992},
editor = {Bernardo, J. M. and Berger, J. O. and Dawid, A. P. and Smith, A. F. M.},
pages = {169-193},
address = {Oxford},
publisher = {University Press},
}
@ARTICLE{Gey:92,
author = {Geyer, C. J.},
title = {Pratical Markov Chain Monte Carlo},
journal = {Statistical Science},
year = {1992},
volume = {7},
number = {4},
pages = {473-511},
}
@ARTICLE{Gil.C.S.B.M.S.K:93,
author = {Gilks, W. R. and Clayton, D. G. and Spiegelhalter, D. J. and Best, N. G. and McNeil, A. J. and Sharples, L. D. and Kirby, A. J.},
title = {Modelling complexity: applications of Gibbs sampling in medicine},
journal = {Journal of the Royal Statistical Society B},
year = {1993},
volume = {55},
pages = {39-52},
}
@ARTICLE{GilTS:94,
author = {Gilks, W. R. and Thomas, A. and Spiegelhalter, D. J.},
title = {A language and program for complex Bayesian modelling},
journal = {The Statistician},
year = {1994},
volume = {43},
pages = {169-178},
}
@ARTICLE{Gil.B.T:95,
author = {Gilks, W.R. and Best, N.G. and Tan, K.K.C.},
title = {Adaptive rejection Metropolis sampling within Gibbs sampling},
journal = {Applied Statistics},
year = {1995},
volume = {44},
pages = {455-472},
}
@ARTICLE{Gil.W:92,
author = {Gilks, W.R. and Wild, P.},
title = {Adaptive rejection sampling for Gibbs sampling},
journal = {Applied Statistics},
year = {1992},
volume = {41},
pages = {337-348},
}
@TECHREPORT{GreMir,
author = {Green, P. J. and Mira, A.},
title = {Delayed Rejection in Reversible Jump Metropolis-Hastings},
}
@ARTICLE{HanCar:01,
author = {Han, C. and Carlin, B. R.},
title = {Markov Chain Monte Carlo Methods for Computing Bayes Factors: A Comparative Review},
journal = {Journal of the American Statistical Association},
year = {2001},
volume = {96},
number = {455},
pages = {1122-1132},
}
@ARTICLE{Has:70,
author = {Hastings, W.K.},
title = {Monte Carlo sampling methods using Markov chains and their applications},
journal = {Biometrika},
year = {1970},
volume = {57},
pages = {97-109},
}
@ARTICLE{Hei.W:83,
author = {Heidelberger, P. and Welch, P.},
title = {Simulation run length control in the presence of an initial transient},
journal = {Operations Research},
year = {1983},
volume = {31},
pages = {1109-1144},
}
@TECHREPORT{Hig:96,
author = {Higdon, D. M.},
title = {Auxiliary Variable Methods for Markov Chain Monte Carlo with Applications},
institution = {Jasa},
year = {1996},
journal = {Jasa Theory and Methods},
}
@INPROCEEDINGS{Hil.S:92,
author = {Hills, S.E. and Smith, A.F.M.},
title = {Parameterization issues in Bayesian inference},
booktitle = {Bayesian Statistics 4},
year = {1992},
editor = {Bernardo, J.M. and Berger, J.O. and Dawid, A.P. and Smith, A.F.M.},
pages = {227-246},
publisher = {Oxford University Press},
}
@ARTICLE{IhaGen:96,
author = {Ihaka, R. and Gentleman, R.},
title = {R: A Language for Data Analysis and Graphics},
journal = {Journal of Computational and Graphical Statistics},
year = {1996},
volume = {5},
number = {3},
pages = {299-314},
}
@ARTICLE{Ing:94,
author = {Ingrassia, S.},
title = {On the rate of convergence of the Metropolis algorithm and Gibbs sampler by geometric bounds},
journal = {The Annals of Applied Probability},
year = {1994},
volume = {31},
pages = {347-389},
}
@ARTICLE{JonHob:01,
author = {Jones, G. L. and Hobert, J. P.},
title = {Honest Exploration of Intractable Probability Distributions via Markov Chain Monte Carlo},
journal = {Statistical Science},
year = {2001},
volume = {16},
number = {4},
pages = {312-334},
}
@ARTICLE{KasRaf:95,
author = {Kass, R. E. and Raftery, A.E.},
title = {Bayes Factors},
journal = {Journal of the American Statistical Association},
year = {1995},
volume = {90},
number = {430},
pages = {773-795},
}
@ARTICLE{Kas.C.G.N:98,
author = {Kass, R.E. and Carlin, B.P. and Gelman, A. and Neal, R.M.},
title = {Markov chain Monte Carlo in practice: a roundtable discussion},
journal = {The American Statistician},
year = {1998},
volume = {52},
pages = {93-100},
}
@INPROCEEDINGS{Key.P.S:98,
author = {Key, J.T. and Pericchi, L.R. and Smith, A.F.M.},
title = {Bayesian model choice: what and why?},
booktitle = {Bayesian Statistics 6},
year = {1998},
editor = {Bernardo, J.M. and Berger, J.O. and Dawid, A.P. and Smith, A.F.M.},
pages = {0-0},
publisher = {Oxford University Press},
}
@ARTICLE{Leo:78,
author = {Leonard, T.},
title = {Density estimation, stochastic processes and prior information},
journal = {Journal of the Royal Statistical Society B},
year = {1978},
volume = {40},
pages = {113-146},
}
@TECHREPORT{Liu,
author = {Liu, J. S.},
title = {Metropolized Independent Sampling with Comparisons to Rejection Sampling and Importance Sampling},
institution = {Department of Statistics, Stanford University},
}
@TECHREPORT{Liu2,
author = {Liu, J. S.},
title = {Markov Chain Monte Carlo and Related Topics},
institution = {Department of Statistics, Stanford University},
}
@TECHREPORT{MacPer:96,
author = {MacEachern, S. N. and Peruggia, M.},
title = {Subsampling the Gibbs Sampler: Variance Reduction},
institution = {Department of Statistics, The Ohio State University},
year = {1996},
}
@ARTICLE{Mac.B:94,
author = {MacEachern, S.N. and Berliner, L.M.},
title = {Subsampling the Gibbs sampler},
journal = {The American Statistician},
year = {1994},
volume = {48},
pages = {188-190},
}
@MANUAL{Splus:98,
title = {S-Plus: Version 4.5},
author = {MathSoft},
organization = {Data Analysis Products Division, MathSoft, Inc.},
address = {Seatle},
year = {1998},
}
@TECHREPORT{WWW,
author = {Mengersen, K.L. and Robert, C.P. and Guihenneuc-Jouyaux},
title = {MCMC convergence diagnostics: a Rclassification},
institution = {Laboratoire de Statistique, CREST, INSEE, Paris},
year = {1998},
number = {16},
}
@ARTICLE{Met:87,
author = {Metropolis, N.},
title = {The beginning of the Monte Carlo method},
journal = {Los Alamos Science},
year = {1987},
number = {Special issue},
pages = {125-130},
}
@ARTICLE{Met.R.R.T.T:53,
author = {Metropolis, N. and Rosenbluth, A.W. and Rosenbluth, M.N. and Teller, A.H. and Teller, E.},
title = {Equations of state calculations by fast computing machine},
journal = {J. Chem. Phys.},
year = {1953},
volume = {21},
pages = {1087-1091},
}
@ARTICLE{MirTie,
author = {Mira, A. and Tierney, L.},
title = {Efficiency and Convergence Properties of Slice Samplers},
journal = {Scand. J. Statist.},
year = {2002},
volume = {29},
pages = {1-12},
institution = {School of Statistics, University of Minnesota},
}
@ARTICLE{Nea:03,
author = {Neal, R. M.},
title = {Slice Sampling},
journal = {The Annals of Statistics},
year = {2003},
volume = {31},
number = {3},
pages = {705-767},
}
@ARTICLE{Nea:01,
author = {Neal, R. M.},
title = {Annealed importance sampling},
journal = {Statistics and Computing},
year = {2001},
volume = {11},
pages = {125-139},
}
@TECHREPORT{Nea:93,
author = {Neal, R. M.},
title = {Probabilistic Inference Using Markov Chain Monte Carlo Methods},
institution = {Department of Computer Science, University of Toronto},
year = {1993},
}
@ARTICLE{NeaSam:97,
author = {Neath, A. A. and Samaniego, F. J.},
title = {On the Efficacy of Bayesian Inference for Nonidentifiable Models},
journal = {The American Statistician},
year = {1997},
volume = {51},
number = {3},
pages = {225-232},
}
@MANUAL{Fbayes:96,
title = {First Bayes: Version 1.3},
author = {O'Hagan, A.},
organization = {Data Analysis Products Division, MathSoft, Inc.},
address = {Nottingham},
year = {1996},
}
@ARTICLE{PauPer:94,
author = {Paulino, C. D. M. and Pereira, C. A. B.},
title = {On Identifiability of Parametric Statistical Models},
journal = {Journal of the Italian Statistical Society},
year = {1994},
volume = {3},
number = {1},
pages = {125-151},
}
@ARTICLE{Pes:73,
author = {Peskun, P. H.},
title = {Optimum Monte-Carlo sampling using Markov chains},
journal = {Biometrika},
year = {1973},
volume = {60},
number = {3},
pages = {607},
}
@INPROCEEDINGS{Raf.L:92,
author = {Raftery, A.L. and Lewis, S.},
title = {How many iterations in the Gibbs sampler?},
booktitle = {Bayesian Statistics 4},
year = {1992},
editor = {Bernardo, J.M. and Berger,J.O. and Dawid, A.P. and Smith, A.F.M.},
pages = {763-774},
address = {Oxford},
publisher = {University Press},
}
@ARTICLE{Rit.T:92,
author = {Ritter, C. and Tanner, M.A.},
title = {Facilitating the Gibbs sampler: the Gibbs stopper and the Griddy-Gibbs sampler},
journal = {Journal of the American Statistical Association},
year = {1992},
volume = {87},
pages = {861-868},
}
@ARTICLE{Rob:92,
author = {Roberts, G. O.},
title = {Convergence Diagnostics of the Gibbs Sampler},
journal = {Bayesian Statistics},
year = {1992},
volume = {4},
pages = {775-782},
}
@ARTICLE{RobRos:99,
author = {Roberts, G. O. and Rosenthal, J. S.},
title = {Convergence of slice sampler Markov chains},
journal = {Journal of the Royal Statistical Society B},
year = {1999},
volume = {61},
pages = {643-660},
}
@ARTICLE{RobSmi:94,
author = {Roberts, G. O. and Smith, A. F. M.},
title = {Simple conditions for the convergence of the Gibbs sampler and Metropolis-Hastings algorithms},
journal = {Stochastic Processes and their Applications},
year = {1994},
volume = {49},
pages = {207-216},
}
@ARTICLE{Rob.P:94,
author = {Roberts, G.O. and Polson, N.G.},
title = {On the geometric convergence of the Gibbs sampler},
journal = {Journal of the Royal Statistical Society B},
year = {1994},
volume = {56},
pages = {377-384},
}
@ARTICLE{Smi.G:92,
author = {Smith, A.F.M. and Gelfand, A.E.},
title = {Bayesian statistics without tears: a sampling-resampling perspective},
journal = {The American Statistician},
year = {1992},
volume = {46},
pages = {84-88},
}
@ARTICLE{Smi.R:93,
author = {Smith, A.F.M. and Roberts, G.O.},
title = {Bayesian computation via the Gibbs sampler and related Markov chain Monte Carlo methods},
journal = {Journal of the Royal Statistical Society B},
year = {1993},
volume = {55},
pages = {3-23},
}
@MANUAL{BOA,
title = {Bayesian Output Analysis Program (BOA), Version 1.1 User's manual},
author = {Smith, B. J. },
year = {2004},
}
@TECHREPORT{Spi.B.C:98,
author = {Spiegelhalter, D. and Best, N. and Carlin, B.P.},
title = {Bayesian deviance, the effective number of parameters, and the comparison of arbitrarily complex models},
institution = {Division of Biostatiscs, University of Minneasota},
year = {1998},
number = {9},
}
@MANUAL{Winbugs:98,
title = {WinBUGS - Bayesian inference using Gibbs sampling for Windows: Version 1.1.1},
author = {Spiegelhalter, D. and Thomas, A. and Best, N.},
organization = {MRC Biostatistics Unit},
address = {Cambrigde},
year = {1998},
}
@MANUAL{Bugs:97,
title = {BUGS - Bayesian inference using Gibbs sampling: Version 0.6},
author = {Spiegelhalter, D. and Thomas, A. and Best, N. and Gilks, W.},
organization = {MRC Biostatistics Unit},
address = {Cambrigde},
year = {1997},
}
@ARTICLE{Spial:02,
author = {Spiegelhalter, D. J. and Best, N. G. and Carlin, B. P. and van der Linde, A.},
title = {Bayesian Measures of model complexity and fit},
journal = {Journal of the Royal Statistical Society B},
year = {2002},
number = {64},
pages = {583-639},
}
@MANUAL{Stata:97,
title = {Stata Statistical Software: Release 5.0},
author = {Stata-Corporation},
organization = {College Station, Stata Corporation},
address = {Texas},
year = {1997},
}
@UNPUBLISHED{Ste:03,
author = {Steinhaus, S.},
title = {Comparison of mathematical programs for data analysis},
year = {2003},
url = {http://www.scientificweb.com/ncrunch/ncrunch4.pdf},
}
@TECHREPORT{StrTwe:98,
author = {Stramer, O. and Tweedie, R. L.},
title = {Self-Targeting Candidates for Metropolis-Hastings Algorithms },
institution = {University of Iowa and Colorado State University },
year = {1998},
}
@ARTICLE{Tan.W:87,
author = {Tanner, M.A. and Wong, W.H.},
title = {The calculation of posterior distributions by data augmentation (with discussion)},
journal = {Journal of the American Statistical Association},
year = {1987},
volume = {82},
pages = {528-550},
}
@INPROCEEDINGS{Tho.S.G:92,
author = {Thomas, A. and Spiegelhalter, D.J. and Gilks, W.R.},
title = {BUGS: a program to perform Bayesian inference using Gibbs sampling},
booktitle = {Bayesian Statistics 4},
year = {1992},
editor = {Bernardo, J.M. and Berger, J.O. and Dawid, A.P. and Smith, A.F.M.},
pages = {837-842},
publisher = {Oxford University Press},
}
@ARTICLE{Tie:94,
author = {Tierney, L.},
title = {Markov chains for exploring posterior distributions},
journal = {The Annals of Statistics},
year = {1994},
volume = {22},
pages = {1701-1762},
}
@ARTICLE{TieMir:99,
author = {Tierney, L. and Mira, A.},
title = {Some Adaptive Monte Carlo Methods For Bayesian Inference},
journal = {Statistics in Medicine},
year = {1999},
number = {18},
pages = {2507-2515},
}
@ARTICLE{VanMen:01,
author = {Van Dyk, D. A. and Meng, X.},
title = {The Art of Data Augmentation},
journal = {Journal of the American Statistical Association},
year = {2001},
volume = {10},
number = {1},
pages = {1-50},
}
@ARTICLE{Wil.G:93,
author = {Wild, P. and Gilks, W.R.},
title = {Adaptive rejection sampling for log-concave density functions},
journal = {Applied Statistics},
year = {1993},
volume = {42},
pages = {701-709},
}
@BOOK{Wol:03,
title = {The Mathematica Book},
publisher = {Wolfram Media/Cambridge University Press},
year = {2003},
author = {Wolfram, S.},
edition = {Fifth},
}
@ARTICLE{Zel.M:95,
author = {Zellner, A. and Min, C.},
title = {Gibbs sampler convergence criteria},
journal = {Journal of the American Statistical Association},
year = {1995},
volume = {90},
pages = {921-927},
}
}}}
Como se pode ver em <<cite AgaGel:03 bibliography:Bibliography>> o exemplo não é muito feliz <<cite CasLAvRob:01>> é uma referência obrigatória <<cite CheShaIbr:00>>, <<cite Coda:97 showAll:true>> <<cite Coda:97>>, <<cite Gew:92>>, <<cite GelMen:96>>, <<cite Ste:03>>
<<bibliography Bibliography>>
/***
|''Name:''|CryptoFunctionsPlugin|
|''Description:''|Support for cryptographic functions|
***/
//{{{
if(!version.extensions.CryptoFunctionsPlugin) {
version.extensions.CryptoFunctionsPlugin = {installed:true};
//--
//-- Crypto functions and associated conversion routines
//--
// Crypto "namespace"
function Crypto() {}
// Convert a string to an array of big-endian 32-bit words
Crypto.strToBe32s = function(str)
{
var be = Array();
var len = Math.floor(str.length/4);
var i, j;
for(i=0, j=0; i<len; i++, j+=4) {
be[i] = ((str.charCodeAt(j)&0xff) << 24)|((str.charCodeAt(j+1)&0xff) << 16)|((str.charCodeAt(j+2)&0xff) << 8)|(str.charCodeAt(j+3)&0xff);
}
while (j<str.length) {
be[j>>2] |= (str.charCodeAt(j)&0xff)<<(24-(j*8)%32);
j++;
}
return be;
};
// Convert an array of big-endian 32-bit words to a string
Crypto.be32sToStr = function(be)
{
var str = "";
for(var i=0;i<be.length*32;i+=8)
str += String.fromCharCode((be[i>>5]>>>(24-i%32)) & 0xff);
return str;
};
// Convert an array of big-endian 32-bit words to a hex string
Crypto.be32sToHex = function(be)
{
var hex = "0123456789ABCDEF";
var str = "";
for(var i=0;i<be.length*4;i++)
str += hex.charAt((be[i>>2]>>((3-i%4)*8+4))&0xF) + hex.charAt((be[i>>2]>>((3-i%4)*8))&0xF);
return str;
};
// Return, in hex, the SHA-1 hash of a string
Crypto.hexSha1Str = function(str)
{
return Crypto.be32sToHex(Crypto.sha1Str(str));
};
// Return the SHA-1 hash of a string
Crypto.sha1Str = function(str)
{
return Crypto.sha1(Crypto.strToBe32s(str),str.length);
};
// Calculate the SHA-1 hash of an array of blen bytes of big-endian 32-bit words
Crypto.sha1 = function(x,blen)
{
// Add 32-bit integers, wrapping at 32 bits
add32 = function(a,b)
{
var lsw = (a&0xFFFF)+(b&0xFFFF);
var msw = (a>>16)+(b>>16)+(lsw>>16);
return (msw<<16)|(lsw&0xFFFF);
};
// Add five 32-bit integers, wrapping at 32 bits
add32x5 = function(a,b,c,d,e)
{
var lsw = (a&0xFFFF)+(b&0xFFFF)+(c&0xFFFF)+(d&0xFFFF)+(e&0xFFFF);
var msw = (a>>16)+(b>>16)+(c>>16)+(d>>16)+(e>>16)+(lsw>>16);
return (msw<<16)|(lsw&0xFFFF);
};
// Bitwise rotate left a 32-bit integer by 1 bit
rol32 = function(n)
{
return (n>>>31)|(n<<1);
};
var len = blen*8;
// Append padding so length in bits is 448 mod 512
x[len>>5] |= 0x80 << (24-len%32);
// Append length
x[((len+64>>9)<<4)+15] = len;
var w = Array(80);
var k1 = 0x5A827999;
var k2 = 0x6ED9EBA1;
var k3 = 0x8F1BBCDC;
var k4 = 0xCA62C1D6;
var h0 = 0x67452301;
var h1 = 0xEFCDAB89;
var h2 = 0x98BADCFE;
var h3 = 0x10325476;
var h4 = 0xC3D2E1F0;
for(var i=0;i<x.length;i+=16) {
var j,t;
var a = h0;
var b = h1;
var c = h2;
var d = h3;
var e = h4;
for(j = 0;j<16;j++) {
w[j] = x[i+j];
t = add32x5(e,(a>>>27)|(a<<5),d^(b&(c^d)),w[j],k1);
e=d; d=c; c=(b>>>2)|(b<<30); b=a; a = t;
}
for(j=16;j<20;j++) {
w[j] = rol32(w[j-3]^w[j-8]^w[j-14]^w[j-16]);
t = add32x5(e,(a>>>27)|(a<<5),d^(b&(c^d)),w[j],k1);
e=d; d=c; c=(b>>>2)|(b<<30); b=a; a = t;
}
for(j=20;j<40;j++) {
w[j] = rol32(w[j-3]^w[j-8]^w[j-14]^w[j-16]);
t = add32x5(e,(a>>>27)|(a<<5),b^c^d,w[j],k2);
e=d; d=c; c=(b>>>2)|(b<<30); b=a; a = t;
}
for(j=40;j<60;j++) {
w[j] = rol32(w[j-3]^w[j-8]^w[j-14]^w[j-16]);
t = add32x5(e,(a>>>27)|(a<<5),(b&c)|(d&(b|c)),w[j],k3);
e=d; d=c; c=(b>>>2)|(b<<30); b=a; a = t;
}
for(j=60;j<80;j++) {
w[j] = rol32(w[j-3]^w[j-8]^w[j-14]^w[j-16]);
t = add32x5(e,(a>>>27)|(a<<5),b^c^d,w[j],k4);
e=d; d=c; c=(b>>>2)|(b<<30); b=a; a = t;
}
h0 = add32(h0,a);
h1 = add32(h1,b);
h2 = add32(h2,c);
h3 = add32(h3,d);
h4 = add32(h4,e);
}
return Array(h0,h1,h2,h3,h4);
};
}
//}}}
/***
|''Name:''|DataTiddlerPlugin|
|''Version:''|1.0.6 (2006-08-26)|
|''Source:''|http://tiddlywiki.abego-software.de/#DataTiddlerPlugin|
|''Author:''|UdoBorkowski (ub [at] abego-software [dot] de)|
|''Licence:''|[[BSD open source license]]|
|''TiddlyWiki:''|1.2.38+, 2.0|
|''Browser:''|Firefox 1.0.4+; InternetExplorer 6.0|
!Description
Enhance your tiddlers with structured data (such as strings, booleans, numbers, or even arrays and compound objects) that can be easily accessed and modified through named fields (in JavaScript code).
Such tiddler data can be used in various applications. E.g. you may create tables that collect data from various tiddlers.
''//Example: "Table with all December Expenses"//''
{{{
<<forEachTiddler
where
'tiddler.tags.contains("expense") && tiddler.data("month") == "Dec"'
write
'"|[["+tiddler.title+"]]|"+tiddler.data("descr")+"| "+tiddler.data("amount")+"|\n"'
>>
}}}
//(This assumes that expenses are stored in tiddlers tagged with "expense".)//
<<forEachTiddler
where
'tiddler.tags.contains("expense") && tiddler.data("month") == "Dec"'
write
'"|[["+tiddler.title+"]]|"+tiddler.data("descr")+"| "+tiddler.data("amount")+"|\n"'
>>
For other examples see DataTiddlerExamples.
''Access and Modify Tiddler Data''
You can "attach" data to every tiddler by assigning a JavaScript value (such as a string, boolean, number, or even arrays and compound objects) to named fields.
These values can be accessed and modified through the following Tiddler methods:
|!Method|!Example|!Description|
|{{{data(field)}}}|{{{t.data("age")}}}|Returns the value of the given data field of the tiddler. When no such field is defined or its value is undefined {{{undefined}}} is returned.|
|{{{data(field,defaultValue)}}}|{{{t.data("isVIP",false)}}}|Returns the value of the given data field of the tiddler. When no such field is defined or its value is undefined the defaultValue is returned.|
|{{{data()}}}|{{{t.data()}}}|Returns the data object of the tiddler, with a property for every field. The properties of the returned data object may only be read and not be modified. To modify the data use DataTiddler.setData(...) or the corresponding Tiddler method.|
|{{{setData(field,value)}}}|{{{t.setData("age",42)}}}|Sets the value of the given data field of the tiddler to the value. When the value is {{{undefined}}} the field is removed.|
|{{{setData(field,value,defaultValue)}}}|{{{t.setData("isVIP",flag,false)}}}|Sets the value of the given data field of the tiddler to the value. When the value is equal to the defaultValue no value is set (and the field is removed).|
Alternatively you may use the following functions to access and modify the data. In this case the tiddler argument is either a tiddler or the name of a tiddler.
|!Method|!Description|
|{{{DataTiddler.getData(tiddler,field)}}}|Returns the value of the given data field of the tiddler. When no such field is defined or its value is undefined {{{undefined}}} is returned.|
|{{{DataTiddler.getData(tiddler,field,defaultValue)}}}|Returns the value of the given data field of the tiddler. When no such field is defined or its value is undefined the defaultValue is returned.|
|{{{DataTiddler.getDataObject(tiddler)}}}|Returns the data object of the tiddler, with a property for every field. The properties of the returned data object may only be read and not be modified. To modify the data use DataTiddler.setData(...) or the corresponding Tiddler method.|
|{{{DataTiddler.setData(tiddler,field,value)}}}|Sets the value of the given data field of the tiddler to the value. When the value is {{{undefined}}} the field is removed.|
|{{{DataTiddler.setData(tiddler,field,value,defaultValue)}}}|Sets the value of the given data field of the tiddler to the value. When the value is equal to the defaultValue no value is set (and the field is removed).|
//(For details on the various functions see the detailed comments in the source code.)//
''Data Representation in a Tiddler''
The data of a tiddler is stored as plain text in the tiddler's content/text, inside a "data" section that is framed by a {{{<data>...</data>}}} block. Inside the data section the information is stored in the [[JSON format|http://www.crockford.com/JSON/index.html]].
//''Data Section Example:''//
{{{
<data>{"isVIP":true,"user":"John Brown","age":34}</data>
}}}
The data section is not displayed when viewing the tiddler (see also "The showData Macro").
Beside the data section a tiddler may have all kind of other content.
Typically you will not access the data section text directly but use the methods given above. Nevertheless you may retrieve the text of the data section's content through the {{{DataTiddler.getDataText(tiddler)}}} function.
''Saving Changes''
The "setData" methods respect the "ForceMinorUpdate" and "AutoSave" configuration values. I.e. when "ForceMinorUpdate" is true changing a value using setData will not affect the "modifier" and "modified" attributes. With "AutoSave" set to true every setData will directly save the changes after a setData.
''Notifications''
No notifications are sent when a tiddler's data value is changed through the "setData" methods.
''Escape Data Section''
In case that you want to use the text {{{<data>}}} or {{{</data>}}} in a tiddler text you must prefix the text with a tilde ('~'). Otherwise it may be wrongly considered as the data section. The tiddler text {{{~<data>}}} is displayed as {{{<data>}}}.
''The showData Macro''
By default the data of a tiddler (that is stored in the {{{<data>...</data>}}} section of the tiddler) is not displayed. If you want to display this data you may used the {{{<<showData ...>>}}} macro:
''Syntax:''
|>|{{{<<}}}''showData '' [''JSON''] [//tiddlerName//] {{{>>}}}|
|''JSON''|By default the data is rendered as a table with a "Name" and "Value" column. When defining ''JSON'' the data is rendered in JSON format|
|//tiddlerName//|Defines the tiddler holding the data to be displayed. When no tiddler is given the tiddler containing the showData macro is used. When the tiddler name contains spaces you must quote the name (or use the {{{[[...]]}}} syntax.)|
|>|~~Syntax formatting: Keywords in ''bold'', optional parts in [...]. 'or' means that exactly one of the two alternatives must exist.~~|
!Revision history
* v1.0.6 (2006-08-26)
** Removed misleading comment
* v1.0.5 (2006-02-27) (Internal Release Only)
** Internal
*** Make "JSLint" conform
* v1.0.4 (2006-02-05)
** Bugfix: showData fails in TiddlyWiki 2.0
* v1.0.3 (2006-01-06)
** Support TiddlyWiki 2.0
* v1.0.2 (2005-12-22)
** Enhancements:
*** Handle texts "<data>" or "</data>" more robust when used in a tiddler text or as a field value.
*** Improved (JSON) error messages.
** Bugs fixed:
*** References are not updated when using the DataTiddler.
*** Changes to compound objects are not always saved.
*** "~</data>" is not rendered correctly (expected "</data>")
* v1.0.1 (2005-12-13)
** Features:
*** The showData macro supports an optional "tiddlername" argument to specify the tiddler containing the data to be displayed
** Bugs fixed:
*** A script immediately following a data section is deleted when the data is changed. (Thanks to GeoffS for reporting.)
* v1.0.0 (2005-12-12)
** initial version
!Code
***/
//{{{
//============================================================================
//============================================================================
// DataTiddlerPlugin
//============================================================================
//============================================================================
// Ensure that the DataTiddler Plugin is only installed once.
//
if (!version.extensions.DataTiddlerPlugin) {
version.extensions.DataTiddlerPlugin = {
major: 1, minor: 0, revision: 6,
date: new Date(2006, 7, 26),
type: 'plugin',
source: "http://tiddlywiki.abego-software.de/#DataTiddlerPlugin"
};
// For backward compatibility with v1.2.x
//
if (!window.story) window.story=window;
if (!TiddlyWiki.prototype.getTiddler) {
TiddlyWiki.prototype.getTiddler = function(title) {
var t = this.tiddlers[title];
return (t !== undefined && t instanceof Tiddler) ? t : null;
};
}
//============================================================================
// DataTiddler Class
//============================================================================
// ---------------------------------------------------------------------------
// Configurations and constants
// ---------------------------------------------------------------------------
function DataTiddler() {
}
DataTiddler = {
// Function to stringify a JavaScript value, producing the text for the data section content.
// (Must match the implementation of DataTiddler.parse.)
//
stringify : null,
// Function to parse the text for the data section content, producing a JavaScript value.
// (Must match the implementation of DataTiddler.stringify.)
//
parse : null
};
// Ensure access for IE
window.DataTiddler = DataTiddler;
// ---------------------------------------------------------------------------
// Data Accessor and Mutator
// ---------------------------------------------------------------------------
// Returns the value of the given data field of the tiddler.
// When no such field is defined or its value is undefined
// the defaultValue is returned.
//
// @param tiddler either a tiddler name or a tiddler
//
DataTiddler.getData = function(tiddler, field, defaultValue) {
var t = (typeof tiddler == "string") ? store.getTiddler(tiddler) : tiddler;
if (!(t instanceof Tiddler)) {
throw "Tiddler expected. Got "+tiddler;
}
return DataTiddler.getTiddlerDataValue(t, field, defaultValue);
};
// Sets the value of the given data field of the tiddler to
// the value. When the value is equal to the defaultValue
// no value is set (and the field is removed)
//
// Changing data of a tiddler will not trigger notifications.
//
// @param tiddler either a tiddler name or a tiddler
//
DataTiddler.setData = function(tiddler, field, value, defaultValue) {
var t = (typeof tiddler == "string") ? store.getTiddler(tiddler) : tiddler;
if (!(t instanceof Tiddler)) {
throw "Tiddler expected. Got "+tiddler+ "("+t+")";
}
DataTiddler.setTiddlerDataValue(t, field, value, defaultValue);
};
// Returns the data object of the tiddler, with a property for every field.
//
// The properties of the returned data object may only be read and
// not be modified. To modify the data use DataTiddler.setData(...)
// or the corresponding Tiddler method.
//
// If no data section is defined a new (empty) object is returned.
//
// @param tiddler either a tiddler name or a Tiddler
//
DataTiddler.getDataObject = function(tiddler) {
var t = (typeof tiddler == "string") ? store.getTiddler(tiddler) : tiddler;
if (!(t instanceof Tiddler)) {
throw "Tiddler expected. Got "+tiddler;
}
return DataTiddler.getTiddlerDataObject(t);
};
// Returns the text of the content of the data section of the tiddler.
//
// When no data section is defined for the tiddler null is returned
//
// @param tiddler either a tiddler name or a Tiddler
// @return [may be null]
//
DataTiddler.getDataText = function(tiddler) {
var t = (typeof tiddler == "string") ? store.getTiddler(tiddler) : tiddler;
if (!(t instanceof Tiddler)) {
throw "Tiddler expected. Got "+tiddler;
}
return DataTiddler.readDataSectionText(t);
};
// ---------------------------------------------------------------------------
// Internal helper methods (must not be used by code from outside this plugin)
// ---------------------------------------------------------------------------
// Internal.
//
// The original JSONError is not very user friendly,
// especially it does not define a toString() method
// Therefore we extend it here.
//
DataTiddler.extendJSONError = function(ex) {
if (ex.name == 'JSONError') {
ex.toString = function() {
return ex.name + ": "+ex.message+" ("+ex.text+")";
};
}
return ex;
};
// Internal.
//
// @param t a Tiddler
//
DataTiddler.getTiddlerDataObject = function(t) {
if (t.dataObject === undefined) {
var data = DataTiddler.readData(t);
t.dataObject = (data) ? data : {};
}
return t.dataObject;
};
// Internal.
//
// @param tiddler a Tiddler
//
DataTiddler.getTiddlerDataValue = function(tiddler, field, defaultValue) {
var value = DataTiddler.getTiddlerDataObject(tiddler)[field];
return (value === undefined) ? defaultValue : value;
};
// Internal.
//
// @param tiddler a Tiddler
//
DataTiddler.setTiddlerDataValue = function(tiddler, field, value, defaultValue) {
var data = DataTiddler.getTiddlerDataObject(tiddler);
var oldValue = data[field];
if (value == defaultValue) {
if (oldValue !== undefined) {
delete data[field];
DataTiddler.save(tiddler);
}
return;
}
data[field] = value;
DataTiddler.save(tiddler);
};
// Internal.
//
// Reads the data section from the tiddler's content and returns its text
// (as a String).
//
// Returns null when no data is defined.
//
// @param tiddler a Tiddler
// @return [may be null]
//
DataTiddler.readDataSectionText = function(tiddler) {
var matches = DataTiddler.getDataTiddlerMatches(tiddler);
if (matches === null || !matches[2]) {
return null;
}
return matches[2];
};
// Internal.
//
// Reads the data section from the tiddler's content and returns it
// (as an internalized object).
//
// Returns null when no data is defined.
//
// @param tiddler a Tiddler
// @return [may be null]
//
DataTiddler.readData = function(tiddler) {
var text = DataTiddler.readDataSectionText(tiddler);
try {
return text ? DataTiddler.parse(text) : null;
} catch(ex) {
throw DataTiddler.extendJSONError(ex);
}
};
// Internal.
//
// Returns the serialized text of the data of the given tiddler, as it
// should be stored in the data section.
//
// @param tiddler a Tiddler
//
DataTiddler.getDataTextOfTiddler = function(tiddler) {
var data = DataTiddler.getTiddlerDataObject(tiddler);
return DataTiddler.stringify(data);
};
// Internal.
//
DataTiddler.indexOfNonEscapedText = function(s, subString, startIndex) {
var index = s.indexOf(subString, startIndex);
while ((index > 0) && (s[index-1] == '~')) {
index = s.indexOf(subString, index+1);
}
return index;
};
// Internal.
//
DataTiddler.getDataSectionInfo = function(text) {
// Special care must be taken to handle "<data>" and "</data>" texts inside
// a data section.
// Also take care not to use an escaped <data> (i.e. "~<data>") as the start
// of a data section. (Same for </data>)
// NOTE: we are explicitly searching for a data section that contains a JSON
// string, i.e. framed with braces. This way we are little bit more robust in
// case the tiddler contains unescaped texts "<data>" or "</data>". This must
// be changed when using a different stringifier.
var startTagText = "<data>{";
var endTagText = "}</data>";
var startPos = 0;
// Find the first not escaped "<data>".
var startDataTagIndex = DataTiddler.indexOfNonEscapedText(text, startTagText, 0);
if (startDataTagIndex < 0) {
return null;
}
// Find the *last* not escaped "</data>".
var endDataTagIndex = text.indexOf(endTagText, startDataTagIndex);
if (endDataTagIndex < 0) {
return null;
}
var nextEndDataTagIndex;
while ((nextEndDataTagIndex = text.indexOf(endTagText, endDataTagIndex+1)) >= 0) {
endDataTagIndex = nextEndDataTagIndex;
}
return {
prefixEnd: startDataTagIndex,
dataStart: startDataTagIndex+(startTagText.length)-1,
dataEnd: endDataTagIndex,
suffixStart: endDataTagIndex+(endTagText.length)
};
};
// Internal.
//
// Returns the "matches" of a content of a DataTiddler on the
// "data" regular expression. Return null when no data is defined
// in the tiddler content.
//
// Group 1: text before data section (prefix)
// Group 2: content of data section
// Group 3: text behind data section (suffix)
//
// @param tiddler a Tiddler
// @return [may be null] null when the tiddler contains no data section, otherwise see above.
//
DataTiddler.getDataTiddlerMatches = function(tiddler) {
var text = tiddler.text;
var info = DataTiddler.getDataSectionInfo(text);
if (!info) {
return null;
}
var prefix = text.substr(0,info.prefixEnd);
var data = text.substr(info.dataStart, info.dataEnd-info.dataStart+1);
var suffix = text.substr(info.suffixStart);
return [text, prefix, data, suffix];
};
// Internal.
//
// Saves the data in a <data> block of the given tiddler (as a minor change).
//
// The "chkAutoSave" and "chkForceMinorUpdate" options are respected.
// I.e. the TiddlyWiki *file* is only saved when AutoSave is on.
//
// Notifications are not send.
//
// This method should only be called when the data really has changed.
//
// @param tiddler
// the tiddler to be saved.
//
DataTiddler.save = function(tiddler) {
var matches = DataTiddler.getDataTiddlerMatches(tiddler);
var prefix;
var suffix;
if (matches === null) {
prefix = tiddler.text;
suffix = "";
} else {
prefix = matches[1];
suffix = matches[3];
}
var dataText = DataTiddler.getDataTextOfTiddler(tiddler);
var newText =
(dataText !== null)
? prefix + "<data>" + dataText + "</data>" + suffix
: prefix + suffix;
if (newText != tiddler.text) {
// make the change in the tiddlers text
// ... see DataTiddler.MyTiddlerChangedFunction
tiddler.isDataTiddlerChange = true;
// ... do the action change
tiddler.set(
tiddler.title,
newText,
config.options.txtUserName,
config.options.chkForceMinorUpdate? undefined : new Date(),
tiddler.tags);
// ... see DataTiddler.MyTiddlerChangedFunction
delete tiddler.isDataTiddlerChange;
// Mark the store as dirty.
store.dirty = true;
// AutoSave if option is selected
if(config.options.chkAutoSave) {
saveChanges();
}
}
};
// Internal.
//
DataTiddler.MyTiddlerChangedFunction = function() {
// Remove the data object from the tiddler when the tiddler is changed
// by code other than DataTiddler code.
//
// This is necessary since the data object is just a "cached version"
// of the data defined in the data section of the tiddler and the
// "external" change may have changed the content of the data section.
// Thus we are not sure if the data object reflects the data section
// contents.
//
// By deleting the data object we ensure that the data object is
// reconstructed the next time it is needed, with the data defined by
// the data section in the tiddler's text.
// To indicate that a change is a "DataTiddler change" a temporary
// property "isDataTiddlerChange" is added to the tiddler.
if (this.dataObject && !this.isDataTiddlerChange) {
delete this.dataObject;
}
// call the original code.
DataTiddler.originalTiddlerChangedFunction.apply(this, arguments);
};
//============================================================================
// Formatters
//============================================================================
// This formatter ensures that "~<data>" is rendered as "<data>". This is used to
// escape the "<data>" of a data section, just in case someone really wants to use
// "<data>" as a text in a tiddler and not start a data section.
//
// Same for </data>.
//
config.formatters.push( {
name: "data-escape",
match: "~<\\/?data>",
handler: function(w) {
w.outputText(w.output,w.matchStart + 1,w.nextMatch);
}
} );
// This formatter ensures that <data>...</data> sections are not rendered.
//
config.formatters.push( {
name: "data",
match: "<data>",
handler: function(w) {
var info = DataTiddler.getDataSectionInfo(w.source);
if (info && info.prefixEnd == w.matchStart) {
w.nextMatch = info.suffixStart;
} else {
w.outputText(w.output,w.matchStart,w.nextMatch);
}
}
} );
//============================================================================
// Tiddler Class Extension
//============================================================================
// "Hijack" the changed method ---------------------------------------------------
DataTiddler.originalTiddlerChangedFunction = Tiddler.prototype.changed;
Tiddler.prototype.changed = DataTiddler.MyTiddlerChangedFunction;
// Define accessor methods -------------------------------------------------------
// Returns the value of the given data field of the tiddler. When no such field
// is defined or its value is undefined the defaultValue is returned.
//
// When field is undefined (or null) the data object is returned. (See
// DataTiddler.getDataObject.)
//
// @param field [may be null, undefined]
// @param defaultValue [may be null, undefined]
// @return [may be null, undefined]
//
Tiddler.prototype.data = function(field, defaultValue) {
return (field)
? DataTiddler.getTiddlerDataValue(this, field, defaultValue)
: DataTiddler.getTiddlerDataObject(this);
};
// Sets the value of the given data field of the tiddler to the value. When the
// value is equal to the defaultValue no value is set (and the field is removed).
//
// @param value [may be null, undefined]
// @param defaultValue [may be null, undefined]
//
Tiddler.prototype.setData = function(field, value, defaultValue) {
DataTiddler.setTiddlerDataValue(this, field, value, defaultValue);
};
//============================================================================
// showData Macro
//============================================================================
config.macros.showData = {
// Standard Properties
label: "showData",
prompt: "Display the values stored in the data section of the tiddler"
};
config.macros.showData.handler = function(place,macroName,params) {
// --- Parsing ------------------------------------------
var i = 0; // index running over the params
// Parse the optional "JSON"
var showInJSONFormat = false;
if ((i < params.length) && params[i] == "JSON") {
i++;
showInJSONFormat = true;
}
var tiddlerName = story.findContainingTiddler(place).id.substr(7);
if (i < params.length) {
tiddlerName = params[i];
i++;
}
// --- Processing ------------------------------------------
try {
if (showInJSONFormat) {
this.renderDataInJSONFormat(place, tiddlerName);
} else {
this.renderDataAsTable(place, tiddlerName);
}
} catch (e) {
this.createErrorElement(place, e);
}
};
config.macros.showData.renderDataInJSONFormat = function(place,tiddlerName) {
var text = DataTiddler.getDataText(tiddlerName);
if (text) {
createTiddlyElement(place,"pre",null,null,text);
}
};
config.macros.showData.renderDataAsTable = function(place,tiddlerName) {
var text = "|!Name|!Value|\n";
var data = DataTiddler.getDataObject(tiddlerName);
if (data) {
for (var i in data) {
var value = data[i];
text += "|"+i+"|"+DataTiddler.stringify(value)+"|\n";
}
}
wikify(text, place);
};
// Internal.
//
// Creates an element that holds an error message
//
config.macros.showData.createErrorElement = function(place, exception) {
var message = (exception.description) ? exception.description : exception.toString();
return createTiddlyElement(place,"span",null,"showDataError","<<showData ...>>: "+message);
};
// ---------------------------------------------------------------------------
// Stylesheet Extensions (may be overridden by local StyleSheet)
// ---------------------------------------------------------------------------
//
setStylesheet(
".showDataError{color: #ffffff;background-color: #880000;}",
"showData");
} // of "install only once"
// Used Globals (for JSLint) ==============
// ... TiddlyWiki Core
/*global createTiddlyElement, saveChanges, store, story, wikify */
// ... DataTiddler
/*global DataTiddler */
// ... JSON
/*global JSON */
/***
!JSON Code, used to serialize the data
***/
/*
Copyright (c) 2005 JSON.org
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 Software shall be used for Good, not Evil.
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.
*/
/*
The global object JSON contains two methods.
JSON.stringify(value) takes a JavaScript value and produces a JSON text.
The value must not be cyclical.
JSON.parse(text) takes a JSON text and produces a JavaScript value. It will
throw a 'JSONError' exception if there is an error.
*/
var JSON = {
copyright: '(c)2005 JSON.org',
license: 'http://www.crockford.com/JSON/license.html',
/*
Stringify a JavaScript value, producing a JSON text.
*/
stringify: function (v) {
var a = [];
/*
Emit a string.
*/
function e(s) {
a[a.length] = s;
}
/*
Convert a value.
*/
function g(x) {
var c, i, l, v;
switch (typeof x) {
case 'object':
if (x) {
if (x instanceof Array) {
e('[');
l = a.length;
for (i = 0; i < x.length; i += 1) {
v = x[i];
if (typeof v != 'undefined' &&
typeof v != 'function') {
if (l < a.length) {
e(',');
}
g(v);
}
}
e(']');
return;
} else if (typeof x.toString != 'undefined') {
e('{');
l = a.length;
for (i in x) {
v = x[i];
if (x.hasOwnProperty(i) &&
typeof v != 'undefined' &&
typeof v != 'function') {
if (l < a.length) {
e(',');
}
g(i);
e(':');
g(v);
}
}
return e('}');
}
}
e('null');
return;
case 'number':
e(isFinite(x) ? +x : 'null');
return;
case 'string':
l = x.length;
e('"');
for (i = 0; i < l; i += 1) {
c = x.charAt(i);
if (c >= ' ') {
if (c == '\\' || c == '"') {
e('\\');
}
e(c);
} else {
switch (c) {
case '\b':
e('\\b');
break;
case '\f':
e('\\f');
break;
case '\n':
e('\\n');
break;
case '\r':
e('\\r');
break;
case '\t':
e('\\t');
break;
default:
c = c.charCodeAt();
e('\\u00' + Math.floor(c / 16).toString(16) +
(c % 16).toString(16));
}
}
}
e('"');
return;
case 'boolean':
e(String(x));
return;
default:
e('null');
return;
}
}
g(v);
return a.join('');
},
/*
Parse a JSON text, producing a JavaScript value.
*/
parse: function (text) {
var p = /^\s*(([,:{}\[\]])|"(\\.|[^\x00-\x1f"\\])*"|-?\d+(\.\d*)?([eE][+-]?\d+)?|true|false|null)\s*/,
token,
operator;
function error(m, t) {
throw {
name: 'JSONError',
message: m,
text: t || operator || token
};
}
function next(b) {
if (b && b != operator) {
error("Expected '" + b + "'");
}
if (text) {
var t = p.exec(text);
if (t) {
if (t[2]) {
token = null;
operator = t[2];
} else {
operator = null;
try {
token = eval(t[1]);
} catch (e) {
error("Bad token", t[1]);
}
}
text = text.substring(t[0].length);
} else {
error("Unrecognized token", text);
}
} else {
token = operator = undefined;
}
}
function val() {
var k, o;
switch (operator) {
case '{':
next('{');
o = {};
if (operator != '}') {
for (;;) {
if (operator || typeof token != 'string') {
error("Missing key");
}
k = token;
next();
next(':');
o[k] = val();
if (operator != ',') {
break;
}
next(',');
}
}
next('}');
return o;
case '[':
next('[');
o = [];
if (operator != ']') {
for (;;) {
o.push(val());
if (operator != ',') {
break;
}
next(',');
}
}
next(']');
return o;
default:
if (operator !== null) {
error("Missing value");
}
k = token;
next();
return k;
}
}
next();
return val();
}
};
/***
!Setup the data serialization
***/
DataTiddler.format = "JSON";
DataTiddler.stringify = JSON.stringify;
DataTiddler.parse = JSON.parse;
//}}}
[[Achille cattura la tartaruga]]
/***
|''Name:''|DeprecatedFunctionsPlugin|
|''Description:''|Support for deprecated functions removed from core|
***/
//{{{
if(!version.extensions.DeprecatedFunctionsPlugin) {
version.extensions.DeprecatedFunctionsPlugin = {installed:true};
//--
//-- Deprecated code
//--
// @Deprecated: Use createElementAndWikify and this.termRegExp instead
config.formatterHelpers.charFormatHelper = function(w)
{
w.subWikify(createTiddlyElement(w.output,this.element),this.terminator);
};
// @Deprecated: Use enclosedTextHelper and this.lookaheadRegExp instead
config.formatterHelpers.monospacedByLineHelper = function(w)
{
var lookaheadRegExp = new RegExp(this.lookahead,"mg");
lookaheadRegExp.lastIndex = w.matchStart;
var lookaheadMatch = lookaheadRegExp.exec(w.source);
if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {
var text = lookaheadMatch[1];
if(config.browser.isIE)
text = text.replace(/\n/g,"\r");
createTiddlyElement(w.output,"pre",null,null,text);
w.nextMatch = lookaheadRegExp.lastIndex;
}
};
// @Deprecated: Use <br> or <br /> instead of <<br>>
config.macros.br = {};
config.macros.br.handler = function(place)
{
createTiddlyElement(place,"br");
};
// Find an entry in an array. Returns the array index or null
// @Deprecated: Use indexOf instead
Array.prototype.find = function(item)
{
var i = this.indexOf(item);
return i == -1 ? null : i;
};
// Load a tiddler from an HTML DIV. The caller should make sure to later call Tiddler.changed()
// @Deprecated: Use store.getLoader().internalizeTiddler instead
Tiddler.prototype.loadFromDiv = function(divRef,title)
{
return store.getLoader().internalizeTiddler(store,this,title,divRef);
};
// Format the text for storage in an HTML DIV
// @Deprecated Use store.getSaver().externalizeTiddler instead.
Tiddler.prototype.saveToDiv = function()
{
return store.getSaver().externalizeTiddler(store,this);
};
// @Deprecated: Use store.allTiddlersAsHtml() instead
function allTiddlersAsHtml()
{
return store.allTiddlersAsHtml();
}
// @Deprecated: Use refreshPageTemplate instead
function applyPageTemplate(title)
{
refreshPageTemplate(title);
}
// @Deprecated: Use story.displayTiddlers instead
function displayTiddlers(srcElement,titles,template,unused1,unused2,animate,unused3)
{
story.displayTiddlers(srcElement,titles,template,animate);
}
// @Deprecated: Use story.displayTiddler instead
function displayTiddler(srcElement,title,template,unused1,unused2,animate,unused3)
{
story.displayTiddler(srcElement,title,template,animate);
}
// @Deprecated: Use functions on right hand side directly instead
var createTiddlerPopup = Popup.create;
var scrollToTiddlerPopup = Popup.show;
var hideTiddlerPopup = Popup.remove;
// @Deprecated: Use right hand side directly instead
var regexpBackSlashEn = new RegExp("\\\\n","mg");
var regexpBackSlash = new RegExp("\\\\","mg");
var regexpBackSlashEss = new RegExp("\\\\s","mg");
var regexpNewLine = new RegExp("\n","mg");
var regexpCarriageReturn = new RegExp("\r","mg");
}
//}}}
Abbiamo calcolato che Achille impiega $t=\frac{a}{v(1-q)}$ secondi per raggiungere la tartaruga. Alla velocità $v$, significa che Achille percorre metri:
$$vt=\frac{a}{v(1-q)}v=\frac{a}{1-q}$$
per raggiungere la tartaruga, dato che $v$ si semplifica.
//~~(Part of the [[ForEachTiddlerPlugin]])~~//
Create customizable lists, tables etc. for your selections of tiddlers. Specify the tiddlers to include and their order through a powerful language.
''Syntax:''
|>|{{{<<}}}''forEachTiddler'' [''in'' //tiddlyWikiPath//] [''where'' //whereCondition//] [''sortBy'' //sortExpression// [''ascending'' //or// ''descending'']] [''script'' //scriptText//] [//action// [//actionParameters//]]{{{>>}}}|
|//tiddlyWikiPath//|The filepath to the TiddlyWiki the macro should work on. When missing the current TiddlyWiki is used.|
|//whereCondition//|(quoted) JavaScript boolean expression. May refer to the build-in variables {{{tiddler}}} and {{{context}}}.|
|//sortExpression//|(quoted) JavaScript expression returning "comparable" objects (using '{{{<}}}','{{{>}}}','{{{==}}}'. May refer to the build-in variables {{{tiddler}}} and {{{context}}}.|
|//scriptText//|(quoted) JavaScript text. Typically defines JavaScript functions that are called by the various JavaScript expressions (whereClause, sortClause, action arguments,...)|
|//action//|The action that should be performed on every selected tiddler, in the given order. By default the actions [[addToList|AddToListAction]] and [[write|WriteAction]] are supported. When no action is specified [[addToList|AddToListAction]] is used.|
|//actionParameters//|(action specific) parameters the action may refer while processing the tiddlers (see action descriptions for details). <<tiddler [[JavaScript in actionParameters]]>>|
|>|~~Syntax formatting: Keywords in ''bold'', optional parts in [...]. 'or' means that exactly one of the two alternatives must exist.~~|
''Using JavaScript''
To give you a lot of flexibility the [[ForEachTiddlerMacro]] uses JavaScript in its arguments. Even if you are not that familiar with JavaScript you may find forEachTiddler useful. Just have a look at the various ready-to-use [[ForEachTiddlerExamples]] and adapt them to your needs.
''The Elements of the Macro''
The arguments of the ForEachTiddlerMacro consist of multiple parts, each of them being optional.
<<slider chkFETInClause [[inClause]] "inClause" "inClause">>
<<slider chkFETWhereClause [[whereClause]] "whereClause" "whereClause">>
<<slider chkFETSortClause [[sortClause]] "sortClause" "sortClause">>
<<slider chkFETScriptClause [[scriptClause]] "scriptClause" "scriptClause">>
<<slider chkFETActions [[Action Specification]] "Action Specification" "Action Specification">>
''Using Macros and ">" inside the forEachTiddler Macro''
You may use other macro calls into the expression, especially in the actionParameters. To avoid that the {{{>>}}} of such a macro call is misinterpreted as the end of the {{{<<forEachTiddler...>>}}} macro you must escape the {{{>>}}} of the inner macro with {{{$))}}} E.g. if you want to use {{{<<tiddler ...>>}}} inside the {{{forEachTiddler}}} macro you have to write {{{<<tiddler ...$))}}}.
In addition it is necessary to escape single {{{>}}} with the text {{{$)}}}.
''Using {{{<<tiddler ... with: ...>>}}} to re-use ForEachTiddler definitions''
Sometimes you may want to use a certain ForEachTiddler definition in slight variations. E.g. you may want to list either the tiddlers tagged with "ToDo" and in the other case with "Done". To do so you may use "Tiddler parameters". Here an example:
Replace the variable part of the ForEachTiddler definition with $1 ($2,... $9 are supported). E.g. you may create the tiddler "ListTaggedTiddlers" like this
{{{
<<forEachTiddler
where
'tiddler.tags.contains("$1")'
>>
}}}
Now you can use the ListTaggedTiddlers for various specific tags, using the {{{<<tiddler ...>>}}} macro:
{{{
<<tiddler ListTaggedTiddlers with: "systemConfig">>
}}}
{{{
<<tiddler ListTaggedTiddlers with: "Plugin">>
}}}
See also [[ForEachTiddlerExamples]].
/***
|''Name:''|ForEachTiddlerPlugin|
|''Version:''|1.0.8 (2007-04-12)|
|''Source:''|http://tiddlywiki.abego-software.de/#ForEachTiddlerPlugin|
|''Author:''|UdoBorkowski (ub [at] abego-software [dot] de)|
|''Licence:''|[[BSD open source license (abego Software)|http://www.abego-software.de/legal/apl-v10.html]]|
|''Copyright:''|© 2005-2007 [[abego Software|http://www.abego-software.de]]|
|''TiddlyWiki:''|1.2.38+, 2.0|
|''Browser:''|Firefox 1.0.4+; Firefox 1.5; InternetExplorer 6.0|
!Description
Create customizable lists, tables etc. for your selections of tiddlers. Specify the tiddlers to include and their order through a powerful language.
''Syntax:''
|>|{{{<<}}}''forEachTiddler'' [''in'' //tiddlyWikiPath//] [''where'' //whereCondition//] [''sortBy'' //sortExpression// [''ascending'' //or// ''descending'']] [''script'' //scriptText//] [//action// [//actionParameters//]]{{{>>}}}|
|//tiddlyWikiPath//|The filepath to the TiddlyWiki the macro should work on. When missing the current TiddlyWiki is used.|
|//whereCondition//|(quoted) JavaScript boolean expression. May refer to the build-in variables {{{tiddler}}} and {{{context}}}.|
|//sortExpression//|(quoted) JavaScript expression returning "comparable" objects (using '{{{<}}}','{{{>}}}','{{{==}}}'. May refer to the build-in variables {{{tiddler}}} and {{{context}}}.|
|//scriptText//|(quoted) JavaScript text. Typically defines JavaScript functions that are called by the various JavaScript expressions (whereClause, sortClause, action arguments,...)|
|//action//|The action that should be performed on every selected tiddler, in the given order. By default the actions [[addToList|AddToListAction]] and [[write|WriteAction]] are supported. When no action is specified [[addToList|AddToListAction]] is used.|
|//actionParameters//|(action specific) parameters the action may refer while processing the tiddlers (see action descriptions for details). <<tiddler [[JavaScript in actionParameters]]>>|
|>|~~Syntax formatting: Keywords in ''bold'', optional parts in [...]. 'or' means that exactly one of the two alternatives must exist.~~|
See details see [[ForEachTiddlerMacro]] and [[ForEachTiddlerExamples]].
!Revision history
* v1.0.8 (2007-04-12)
** Adapted to latest TiddlyWiki 2.2 Beta importTiddlyWiki API (introduced with changeset 2004). TiddlyWiki 2.2 Beta builds prior to changeset 2004 are no longer supported (but TiddlyWiki 2.1 and earlier, of cause)
* v1.0.7 (2007-03-28)
** Also support "pre" formatted TiddlyWikis (introduced with TW 2.2) (when using "in" clause to work on external tiddlers)
* v1.0.6 (2006-09-16)
** Context provides "viewerTiddler", i.e. the tiddler used to view the macro. Most times this is equal to the "inTiddler", but when using the "tiddler" macro both may be different.
** Support "begin", "end" and "none" expressions in "write" action
* v1.0.5 (2006-02-05)
** Pass tiddler containing the macro with wikify, context object also holds reference to tiddler containing the macro ("inTiddler"). Thanks to SimonBaird.
** Support Firefox 1.5.0.1
** Internal
*** Make "JSLint" conform
*** "Only install once"
* v1.0.4 (2006-01-06)
** Support TiddlyWiki 2.0
* v1.0.3 (2005-12-22)
** Features:
*** Write output to a file supports multi-byte environments (Thanks to Bram Chen)
*** Provide API to access the forEachTiddler functionality directly through JavaScript (see getTiddlers and performMacro)
** Enhancements:
*** Improved error messages on InternetExplorer.
* v1.0.2 (2005-12-10)
** Features:
*** context object also holds reference to store (TiddlyWiki)
** Fixed Bugs:
*** ForEachTiddler 1.0.1 has broken support on win32 Opera 8.51 (Thanks to BrunoSabin for reporting)
* v1.0.1 (2005-12-08)
** Features:
*** Access tiddlers stored in separated TiddlyWikis through the "in" option. I.e. you are no longer limited to only work on the "current TiddlyWiki".
*** Write output to an external file using the "toFile" option of the "write" action. With this option you may write your customized tiddler exports.
*** Use the "script" section to define "helper" JavaScript functions etc. to be used in the various JavaScript expressions (whereClause, sortClause, action arguments,...).
*** Access and store context information for the current forEachTiddler invocation (through the build-in "context" object) .
*** Improved script evaluation (for where/sort clause and write scripts).
* v1.0.0 (2005-11-20)
** initial version
!Code
***/
//{{{
//============================================================================
//============================================================================
// ForEachTiddlerPlugin
//============================================================================
//============================================================================
// Only install once
if (!version.extensions.ForEachTiddlerPlugin) {
if (!window.abego) window.abego = {};
version.extensions.ForEachTiddlerPlugin = {
major: 1, minor: 0, revision: 8,
date: new Date(2007,3,12),
source: "http://tiddlywiki.abego-software.de/#ForEachTiddlerPlugin",
licence: "[[BSD open source license (abego Software)|http://www.abego-software.de/legal/apl-v10.html]]",
copyright: "Copyright (c) abego Software GmbH, 2005-2007 (www.abego-software.de)"
};
// For backward compatibility with TW 1.2.x
//
if (!TiddlyWiki.prototype.forEachTiddler) {
TiddlyWiki.prototype.forEachTiddler = function(callback) {
for(var t in this.tiddlers) {
callback.call(this,t,this.tiddlers[t]);
}
};
}
//============================================================================
// forEachTiddler Macro
//============================================================================
version.extensions.forEachTiddler = {
major: 1, minor: 0, revision: 8, date: new Date(2007,3,12), provider: "http://tiddlywiki.abego-software.de"};
// ---------------------------------------------------------------------------
// Configurations and constants
// ---------------------------------------------------------------------------
config.macros.forEachTiddler = {
// Standard Properties
label: "forEachTiddler",
prompt: "Perform actions on a (sorted) selection of tiddlers",
// actions
actions: {
addToList: {},
write: {}
}
};
// ---------------------------------------------------------------------------
// The forEachTiddler Macro Handler
// ---------------------------------------------------------------------------
config.macros.forEachTiddler.getContainingTiddler = function(e) {
while(e && !hasClass(e,"tiddler"))
e = e.parentNode;
var title = e ? e.getAttribute("tiddler") : null;
return title ? store.getTiddler(title) : null;
};
config.macros.forEachTiddler.handler = function(place,macroName,params,wikifier,paramString,tiddler) {
// config.macros.forEachTiddler.traceMacroCall(place,macroName,params,wikifier,paramString,tiddler);
if (!tiddler) tiddler = config.macros.forEachTiddler.getContainingTiddler(place);
// --- Parsing ------------------------------------------
var i = 0; // index running over the params
// Parse the "in" clause
var tiddlyWikiPath = undefined;
if ((i < params.length) && params[i] == "in") {
i++;
if (i >= params.length) {
this.handleError(place, "TiddlyWiki path expected behind 'in'.");
return;
}
tiddlyWikiPath = this.paramEncode((i < params.length) ? params[i] : "");
i++;
}
// Parse the where clause
var whereClause ="true";
if ((i < params.length) && params[i] == "where") {
i++;
whereClause = this.paramEncode((i < params.length) ? params[i] : "");
i++;
}
// Parse the sort stuff
var sortClause = null;
var sortAscending = true;
if ((i < params.length) && params[i] == "sortBy") {
i++;
if (i >= params.length) {
this.handleError(place, "sortClause missing behind 'sortBy'.");
return;
}
sortClause = this.paramEncode(params[i]);
i++;
if ((i < params.length) && (params[i] == "ascending" || params[i] == "descending")) {
sortAscending = params[i] == "ascending";
i++;
}
}
// Parse the script
var scriptText = null;
if ((i < params.length) && params[i] == "script") {
i++;
scriptText = this.paramEncode((i < params.length) ? params[i] : "");
i++;
}
// Parse the action.
// When we are already at the end use the default action
var actionName = "addToList";
if (i < params.length) {
if (!config.macros.forEachTiddler.actions[params[i]]) {
this.handleError(place, "Unknown action '"+params[i]+"'.");
return;
} else {
actionName = params[i];
i++;
}
}
// Get the action parameter
// (the parsing is done inside the individual action implementation.)
var actionParameter = params.slice(i);
// --- Processing ------------------------------------------
try {
this.performMacro({
place: place,
inTiddler: tiddler,
whereClause: whereClause,
sortClause: sortClause,
sortAscending: sortAscending,
actionName: actionName,
actionParameter: actionParameter,
scriptText: scriptText,
tiddlyWikiPath: tiddlyWikiPath});
} catch (e) {
this.handleError(place, e);
}
};
// Returns an object with properties "tiddlers" and "context".
// tiddlers holds the (sorted) tiddlers selected by the parameter,
// context the context of the execution of the macro.
//
// The action is not yet performed.
//
// @parameter see performMacro
//
config.macros.forEachTiddler.getTiddlersAndContext = function(parameter) {
var context = config.macros.forEachTiddler.createContext(parameter.place, parameter.whereClause, parameter.sortClause, parameter.sortAscending, parameter.actionName, parameter.actionParameter, parameter.scriptText, parameter.tiddlyWikiPath, parameter.inTiddler);
var tiddlyWiki = parameter.tiddlyWikiPath ? this.loadTiddlyWiki(parameter.tiddlyWikiPath) : store;
context["tiddlyWiki"] = tiddlyWiki;
// Get the tiddlers, as defined by the whereClause
var tiddlers = this.findTiddlers(parameter.whereClause, context, tiddlyWiki);
context["tiddlers"] = tiddlers;
// Sort the tiddlers, when sorting is required.
if (parameter.sortClause) {
this.sortTiddlers(tiddlers, parameter.sortClause, parameter.sortAscending, context);
}
return {tiddlers: tiddlers, context: context};
};
// Returns the (sorted) tiddlers selected by the parameter.
//
// The action is not yet performed.
//
// @parameter see performMacro
//
config.macros.forEachTiddler.getTiddlers = function(parameter) {
return this.getTiddlersAndContext(parameter).tiddlers;
};
// Performs the macros with the given parameter.
//
// @param parameter holds the parameter of the macro as separate properties.
// The following properties are supported:
//
// place
// whereClause
// sortClause
// sortAscending
// actionName
// actionParameter
// scriptText
// tiddlyWikiPath
//
// All properties are optional.
// For most actions the place property must be defined.
//
config.macros.forEachTiddler.performMacro = function(parameter) {
var tiddlersAndContext = this.getTiddlersAndContext(parameter);
// Perform the action
var actionName = parameter.actionName ? parameter.actionName : "addToList";
var action = config.macros.forEachTiddler.actions[actionName];
if (!action) {
this.handleError(parameter.place, "Unknown action '"+actionName+"'.");
return;
}
var actionHandler = action.handler;
actionHandler(parameter.place, tiddlersAndContext.tiddlers, parameter.actionParameter, tiddlersAndContext.context);
};
// ---------------------------------------------------------------------------
// The actions
// ---------------------------------------------------------------------------
// Internal.
//
// --- The addToList Action -----------------------------------------------
//
config.macros.forEachTiddler.actions.addToList.handler = function(place, tiddlers, parameter, context) {
// Parse the parameter
var p = 0;
// Check for extra parameters
if (parameter.length > p) {
config.macros.forEachTiddler.createExtraParameterErrorElement(place, "addToList", parameter, p);
return;
}
// Perform the action.
var list = document.createElement("ul");
place.appendChild(list);
for (var i = 0; i < tiddlers.length; i++) {
var tiddler = tiddlers[i];
var listItem = document.createElement("li");
list.appendChild(listItem);
createTiddlyLink(listItem, tiddler.title, true);
}
};
abego.parseNamedParameter = function(name, parameter, i) {
var beginExpression = null;
if ((i < parameter.length) && parameter[i] == name) {
i++;
if (i >= parameter.length) {
throw "Missing text behind '%0'".format([name]);
}
return config.macros.forEachTiddler.paramEncode(parameter[i]);
}
return null;
}
// Internal.
//
// --- The write Action ---------------------------------------------------
//
config.macros.forEachTiddler.actions.write.handler = function(place, tiddlers, parameter, context) {
// Parse the parameter
var p = 0;
if (p >= parameter.length) {
this.handleError(place, "Missing expression behind 'write'.");
return;
}
var textExpression = config.macros.forEachTiddler.paramEncode(parameter[p]);
p++;
// Parse the "begin" option
var beginExpression = abego.parseNamedParameter("begin", parameter, p);
if (beginExpression !== null)
p += 2;
var endExpression = abego.parseNamedParameter("end", parameter, p);
if (endExpression !== null)
p += 2;
var noneExpression = abego.parseNamedParameter("none", parameter, p);
if (noneExpression !== null)
p += 2;
// Parse the "toFile" option
var filename = null;
var lineSeparator = undefined;
if ((p < parameter.length) && parameter[p] == "toFile") {
p++;
if (p >= parameter.length) {
this.handleError(place, "Filename expected behind 'toFile' of 'write' action.");
return;
}
filename = config.macros.forEachTiddler.getLocalPath(config.macros.forEachTiddler.paramEncode(parameter[p]));
p++;
if ((p < parameter.length) && parameter[p] == "withLineSeparator") {
p++;
if (p >= parameter.length) {
this.handleError(place, "Line separator text expected behind 'withLineSeparator' of 'write' action.");
return;
}
lineSeparator = config.macros.forEachTiddler.paramEncode(parameter[p]);
p++;
}
}
// Check for extra parameters
if (parameter.length > p) {
config.macros.forEachTiddler.createExtraParameterErrorElement(place, "write", parameter, p);
return;
}
// Perform the action.
var func = config.macros.forEachTiddler.getEvalTiddlerFunction(textExpression, context);
var count = tiddlers.length;
var text = "";
if (count > 0 && beginExpression)
text += config.macros.forEachTiddler.getEvalTiddlerFunction(beginExpression, context)(undefined, context, count, undefined);
for (var i = 0; i < count; i++) {
var tiddler = tiddlers[i];
text += func(tiddler, context, count, i);
}
if (count > 0 && endExpression)
text += config.macros.forEachTiddler.getEvalTiddlerFunction(endExpression, context)(undefined, context, count, undefined);
if (count == 0 && noneExpression)
text += config.macros.forEachTiddler.getEvalTiddlerFunction(noneExpression, context)(undefined, context, count, undefined);
if (filename) {
if (lineSeparator !== undefined) {
lineSeparator = lineSeparator.replace(/\\n/mg, "\n").replace(/\\r/mg, "\r");
text = text.replace(/\n/mg,lineSeparator);
}
saveFile(filename, convertUnicodeToUTF8(text));
} else {
var wrapper = createTiddlyElement(place, "span");
wikify(text, wrapper, null/* highlightRegExp */, context.inTiddler);
}
};
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
// Internal.
//
config.macros.forEachTiddler.createContext = function(placeParam, whereClauseParam, sortClauseParam, sortAscendingParam, actionNameParam, actionParameterParam, scriptText, tiddlyWikiPathParam, inTiddlerParam) {
return {
place : placeParam,
whereClause : whereClauseParam,
sortClause : sortClauseParam,
sortAscending : sortAscendingParam,
script : scriptText,
actionName : actionNameParam,
actionParameter : actionParameterParam,
tiddlyWikiPath : tiddlyWikiPathParam,
inTiddler : inTiddlerParam, // the tiddler containing the <<forEachTiddler ...>> macro call.
viewerTiddler : config.macros.forEachTiddler.getContainingTiddler(placeParam) // the tiddler showing the forEachTiddler result
};
};
// Internal.
//
// Returns a TiddlyWiki with the tiddlers loaded from the TiddlyWiki of
// the given path.
//
config.macros.forEachTiddler.loadTiddlyWiki = function(path, idPrefix) {
if (!idPrefix) {
idPrefix = "store";
}
var lenPrefix = idPrefix.length;
// Read the content of the given file
var content = loadFile(this.getLocalPath(path));
if(content === null) {
throw "TiddlyWiki '"+path+"' not found.";
}
var tiddlyWiki = new TiddlyWiki();
// Starting with TW 2.2 there is a helper function to import the tiddlers
if (tiddlyWiki.importTiddlyWiki) {
if (!tiddlyWiki.importTiddlyWiki(content))
throw "File '"+path+"' is not a TiddlyWiki.";
tiddlyWiki.dirty = false;
return tiddlyWiki;
}
// The legacy code, for TW < 2.2
// Locate the storeArea div's
var posOpeningDiv = content.indexOf(startSaveArea);
var posClosingDiv = content.lastIndexOf(endSaveArea);
if((posOpeningDiv == -1) || (posClosingDiv == -1)) {
throw "File '"+path+"' is not a TiddlyWiki.";
}
var storageText = content.substr(posOpeningDiv + startSaveArea.length, posClosingDiv);
// Create a "div" element that contains the storage text
var myStorageDiv = document.createElement("div");
myStorageDiv.innerHTML = storageText;
myStorageDiv.normalize();
// Create all tiddlers in a new TiddlyWiki
// (following code is modified copy of TiddlyWiki.prototype.loadFromDiv)
var store = myStorageDiv.childNodes;
for(var t = 0; t < store.length; t++) {
var e = store[t];
var title = null;
if(e.getAttribute)
title = e.getAttribute("tiddler");
if(!title && e.id && e.id.substr(0,lenPrefix) == idPrefix)
title = e.id.substr(lenPrefix);
if(title && title !== "") {
var tiddler = tiddlyWiki.createTiddler(title);
tiddler.loadFromDiv(e,title);
}
}
tiddlyWiki.dirty = false;
return tiddlyWiki;
};
// Internal.
//
// Returns a function that has a function body returning the given javaScriptExpression.
// The function has the parameters:
//
// (tiddler, context, count, index)
//
config.macros.forEachTiddler.getEvalTiddlerFunction = function (javaScriptExpression, context) {
var script = context["script"];
var functionText = "var theFunction = function(tiddler, context, count, index) { return "+javaScriptExpression+"}";
var fullText = (script ? script+";" : "")+functionText+";theFunction;";
return eval(fullText);
};
// Internal.
//
config.macros.forEachTiddler.findTiddlers = function(whereClause, context, tiddlyWiki) {
var result = [];
var func = config.macros.forEachTiddler.getEvalTiddlerFunction(whereClause, context);
tiddlyWiki.forEachTiddler(function(title,tiddler) {
if (func(tiddler, context, undefined, undefined)) {
result.push(tiddler);
}
});
return result;
};
// Internal.
//
config.macros.forEachTiddler.createExtraParameterErrorElement = function(place, actionName, parameter, firstUnusedIndex) {
var message = "Extra parameter behind '"+actionName+"':";
for (var i = firstUnusedIndex; i < parameter.length; i++) {
message += " "+parameter[i];
}
this.handleError(place, message);
};
// Internal.
//
config.macros.forEachTiddler.sortAscending = function(tiddlerA, tiddlerB) {
var result =
(tiddlerA.forEachTiddlerSortValue == tiddlerB.forEachTiddlerSortValue)
? 0
: (tiddlerA.forEachTiddlerSortValue < tiddlerB.forEachTiddlerSortValue)
? -1
: +1;
return result;
};
// Internal.
//
config.macros.forEachTiddler.sortDescending = function(tiddlerA, tiddlerB) {
var result =
(tiddlerA.forEachTiddlerSortValue == tiddlerB.forEachTiddlerSortValue)
? 0
: (tiddlerA.forEachTiddlerSortValue < tiddlerB.forEachTiddlerSortValue)
? +1
: -1;
return result;
};
// Internal.
//
config.macros.forEachTiddler.sortTiddlers = function(tiddlers, sortClause, ascending, context) {
// To avoid evaluating the sortClause whenever two items are compared
// we pre-calculate the sortValue for every item in the array and store it in a
// temporary property ("forEachTiddlerSortValue") of the tiddlers.
var func = config.macros.forEachTiddler.getEvalTiddlerFunction(sortClause, context);
var count = tiddlers.length;
var i;
for (i = 0; i < count; i++) {
var tiddler = tiddlers[i];
tiddler.forEachTiddlerSortValue = func(tiddler,context, undefined, undefined);
}
// Do the sorting
tiddlers.sort(ascending ? this.sortAscending : this.sortDescending);
// Delete the temporary property that holds the sortValue.
for (i = 0; i < tiddlers.length; i++) {
delete tiddlers[i].forEachTiddlerSortValue;
}
};
// Internal.
//
config.macros.forEachTiddler.trace = function(message) {
displayMessage(message);
};
// Internal.
//
config.macros.forEachTiddler.traceMacroCall = function(place,macroName,params) {
var message ="<<"+macroName;
for (var i = 0; i < params.length; i++) {
message += " "+params[i];
}
message += ">>";
displayMessage(message);
};
// Internal.
//
// Creates an element that holds an error message
//
config.macros.forEachTiddler.createErrorElement = function(place, exception) {
var message = (exception.description) ? exception.description : exception.toString();
return createTiddlyElement(place,"span",null,"forEachTiddlerError","<<forEachTiddler ...>>: "+message);
};
// Internal.
//
// @param place [may be null]
//
config.macros.forEachTiddler.handleError = function(place, exception) {
if (place) {
this.createErrorElement(place, exception);
} else {
throw exception;
}
};
// Internal.
//
// Encodes the given string.
//
// Replaces
// "$))" to ">>"
// "$)" to ">"
//
config.macros.forEachTiddler.paramEncode = function(s) {
var reGTGT = new RegExp("\\$\\)\\)","mg");
var reGT = new RegExp("\\$\\)","mg");
return s.replace(reGTGT, ">>").replace(reGT, ">");
};
// Internal.
//
// Returns the given original path (that is a file path, starting with "file:")
// as a path to a local file, in the systems native file format.
//
// Location information in the originalPath (i.e. the "#" and stuff following)
// is stripped.
//
config.macros.forEachTiddler.getLocalPath = function(originalPath) {
// Remove any location part of the URL
var hashPos = originalPath.indexOf("#");
if(hashPos != -1)
originalPath = originalPath.substr(0,hashPos);
// Convert to a native file format assuming
// "file:///x:/path/path/path..." - pc local file --> "x:\path\path\path..."
// "file://///server/share/path/path/path..." - FireFox pc network file --> "\\server\share\path\path\path..."
// "file:///path/path/path..." - mac/unix local file --> "/path/path/path..."
// "file://server/share/path/path/path..." - pc network file --> "\\server\share\path\path\path..."
var localPath;
if(originalPath.charAt(9) == ":") // pc local file
localPath = unescape(originalPath.substr(8)).replace(new RegExp("/","g"),"\\");
else if(originalPath.indexOf("file://///") === 0) // FireFox pc network file
localPath = "\\\\" + unescape(originalPath.substr(10)).replace(new RegExp("/","g"),"\\");
else if(originalPath.indexOf("file:///") === 0) // mac/unix local file
localPath = unescape(originalPath.substr(7));
else if(originalPath.indexOf("file:/") === 0) // mac/unix local file
localPath = unescape(originalPath.substr(5));
else // pc network file
localPath = "\\\\" + unescape(originalPath.substr(7)).replace(new RegExp("/","g"),"\\");
return localPath;
};
// ---------------------------------------------------------------------------
// Stylesheet Extensions (may be overridden by local StyleSheet)
// ---------------------------------------------------------------------------
//
setStylesheet(
".forEachTiddlerError{color: #ffffff;background-color: #880000;}",
"forEachTiddler");
//============================================================================
// End of forEachTiddler Macro
//============================================================================
//============================================================================
// String.startsWith Function
//============================================================================
//
// Returns true if the string starts with the given prefix, false otherwise.
//
version.extensions["String.startsWith"] = {major: 1, minor: 0, revision: 0, date: new Date(2005,11,20), provider: "http://tiddlywiki.abego-software.de"};
//
String.prototype.startsWith = function(prefix) {
var n = prefix.length;
return (this.length >= n) && (this.slice(0, n) == prefix);
};
//============================================================================
// String.endsWith Function
//============================================================================
//
// Returns true if the string ends with the given suffix, false otherwise.
//
version.extensions["String.endsWith"] = {major: 1, minor: 0, revision: 0, date: new Date(2005,11,20), provider: "http://tiddlywiki.abego-software.de"};
//
String.prototype.endsWith = function(suffix) {
var n = suffix.length;
return (this.length >= n) && (this.right(n) == suffix);
};
//============================================================================
// String.contains Function
//============================================================================
//
// Returns true when the string contains the given substring, false otherwise.
//
version.extensions["String.contains"] = {major: 1, minor: 0, revision: 0, date: new Date(2005,11,20), provider: "http://tiddlywiki.abego-software.de"};
//
String.prototype.contains = function(substring) {
return this.indexOf(substring) >= 0;
};
//============================================================================
// Array.indexOf Function
//============================================================================
//
// Returns the index of the first occurance of the given item in the array or
// -1 when no such item exists.
//
// @param item [may be null]
//
version.extensions["Array.indexOf"] = {major: 1, minor: 0, revision: 0, date: new Date(2005,11,20), provider: "http://tiddlywiki.abego-software.de"};
//
Array.prototype.indexOf = function(item) {
for (var i = 0; i < this.length; i++) {
if (this[i] == item) {
return i;
}
}
return -1;
};
//============================================================================
// Array.contains Function
//============================================================================
//
// Returns true when the array contains the given item, otherwise false.
//
// @param item [may be null]
//
version.extensions["Array.contains"] = {major: 1, minor: 0, revision: 0, date: new Date(2005,11,20), provider: "http://tiddlywiki.abego-software.de"};
//
Array.prototype.contains = function(item) {
return (this.indexOf(item) >= 0);
};
//============================================================================
// Array.containsAny Function
//============================================================================
//
// Returns true when the array contains at least one of the elements
// of the item. Otherwise (or when items contains no elements) false is returned.
//
version.extensions["Array.containsAny"] = {major: 1, minor: 0, revision: 0, date: new Date(2005,11,20), provider: "http://tiddlywiki.abego-software.de"};
//
Array.prototype.containsAny = function(items) {
for(var i = 0; i < items.length; i++) {
if (this.contains(items[i])) {
return true;
}
}
return false;
};
//============================================================================
// Array.containsAll Function
//============================================================================
//
// Returns true when the array contains all the items, otherwise false.
//
// When items is null false is returned (even if the array contains a null).
//
// @param items [may be null]
//
version.extensions["Array.containsAll"] = {major: 1, minor: 0, revision: 0, date: new Date(2005,11,20), provider: "http://tiddlywiki.abego-software.de"};
//
Array.prototype.containsAll = function(items) {
for(var i = 0; i < items.length; i++) {
if (!this.contains(items[i])) {
return false;
}
}
return true;
};
} // of "install only once"
// Used Globals (for JSLint) ==============
// ... DOM
/*global document */
// ... TiddlyWiki Core
/*global convertUnicodeToUTF8, createTiddlyElement, createTiddlyLink,
displayMessage, endSaveArea, hasClass, loadFile, saveFile,
startSaveArea, store, wikify */
//}}}
/***
!Licence and Copyright
Copyright (c) abego Software ~GmbH, 2005 ([[www.abego-software.de|http://www.abego-software.de]])
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 abego Software 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.
***/
The [[FormTiddlerPlugin]] allows you to enter your data in a form and store the form's data in your tiddlers.
(For more information on tiddler data see the [[DataTiddlerPlugin]].)
//''Define ~FormTemplate''//
When you want to enter data in a form you first have to define a [[FormTemplate]] tiddler. A FormTemplate tiddler is a tiddler that contains named HTML INPUT elements (such as textfields, password fields, lists etc.) that define the stuff that should be edited in the form. E.g. you may have a FormTemplate that looks like this:
<html>
<b>Name:</b><br/>
<input name=userName type=text /><br/>
<b>Password:</b><br/>
<input name=pwd type=password /><br/>
</html>
The correspond HTML text looks like this
{{{
<html>
<b>Name:</b><br/>
<input name=userName type=text /><br/>
<b>Password:</b><br/>
<input name=pwd type=password /><br/>
</html>
}}}
The name of the INPUT element is also the name of the data field it is editing. E.g. a text field defined like this:
{{{
<input name=userName type=text />
}}}
will edit the data field "userName" of the tiddler.
You are free to layout the INPUT elements as you like, but don't add a "form" element around them and don't define 'onchange' handlers, since this will be done automatically by the {{{<<formTiddler ...>>}}} macro.
//''Use ~FormTemplates (through the {{{<<formTiddler ...>>}}} macro)''//
In a second step you add the {{{<<formTiddler ...>>}}} macro to tiddlers that should be edited. In the macro you are referencing the [[FormTemplate]] that should be used to edit the tiddler's data. You may refer to the same FormTemplate tiddler in as many tiddlers as you like. Every such tiddler displays the same INPUT elements as the FormTemplate, but with the "data" of each individual tiddler.
In addition you may more than one {{{<<formTiddler...>>}}} macro call in one tiddler. Just make sure that the names of the elements in the referenced FormTemplate tiddlers do not collide. This feature may be useful if you want to construct a larger input form from a set of smaller FormTemplates.
You can easily create tiddlers with an embedded {{{<<formTiddler...>>}}} macro call using the [[<<newTiddlerWithForm...>>|NewTiddlerWithFormMacro]] macro. The macro shows a button similar to the "new tiddler" button and creates the requested tiddler, ready to enter data. For details see NewTiddlerWithFormMacro.
//''"Structured" and "Free" Data''//
Typically you will edit a tiddler that uses the {{{<<formTiddler...>>}}} macro through the form. But you are free to also edit the tiddler "as usual", through the build-in edit feature. I.e. you may mix "structured data" (as entered through the form) with "free data". I.e. on a "Contact" tiddler you may add an image to the tiddler, or add extra links to related persons. Or you add more tags. Just make sure that you don't modify the {{{<data>...</data>}}} section of the tiddler, since this contains the data maintained by the form.
Also notice that since the data entered in the forms is stored in the tiddler's text (in the {{{<data>...</data>}}} section) using the "search" feature will also find the texts you entered in the forms (even though it will not hilite the texts in the fields).
//''Applications''//
Using the [[FormTiddlerPlugin]] it is easy to manage things like:
* [[Contacts]]
* [[Bugreports]]
* ~ToDo Lists
* and many more.
Since a FormTemplate is typically used for many tiddlers of the same kind you may also consider using the ForEachTiddlerMacro to collect data across multiple tiddlers (e.g. to get a list of all contacts, a summary page for the bug reports etc.)
(See also [[FormTiddler Examples]])
//''HTML Elements''//
For those not that familiar with the HTML INPUT elements here a short overview with HTML snippets.
|!Type|!HTML Example|!Comment|
|button|{{{<input name=btn type=button value="Just a button" />}}}|no data|
|checkbox|{{{<input name=isVIP type=checkbox />is VIP}}}||
|file|{{{<input name=attachment type=file />}}}|The "file" input element typically does not restore the path of the previously selected file. Nevertheless the path of the file is stored in the tiddler.|
|hidden|{{{<input name=hiddenValue type=hidden value="This is a hidden value" />}}}||
|password|{{{<input name=pwd type=password />}}}|The data entered in a "password" field is stored as clear text in the tiddler.|
|radio|{{{<input name=level type=radio value="Beginner" />Beginner<input name=level type=radio value="Expert" />Expert<input name=level type=radio value="Guru" />Guru}}}||
|reset|{{{<input name=btnReset type=reset />}}}|no data|
|select-one|{{{<select name=browser ><option>Firefox<option>Internet Explorer<option>Opera<option>Other</select >}}}||
|select-multiple|{{{<select name=music MULTIPLE ><option> R&B <option> Jazz <option> Blues <option> New Age</select >}}}||
|submit|{{{<input name=btnSubmit type=submit />}}}|no data|
|text|{{{<input name=userName type=text/>}}}||
|textarea|{{{<TEXTAREA name=notes rows=4 cols=80 ></TEXTAREA>}}}||
For details consult the Web or a textbook on HTML editing.
The {{{<<formTiddler ...>>}}} macro defined by the FormTiddlerPlugin.
When a tiddler T1 references the (FormTemplate) tiddler T2 in the FormTiddlerMacro, the data of T1 can be edited through the INPUT elements defined by T2.
/***
<<checkForDataTiddlerPlugin>>
|''Name:''|FormTiddlerPlugin|
|''Version:''|1.0.6 (2007-06-24)|
|''Source:''|http://tiddlywiki.abego-software.de/#FormTiddlerPlugin|
|''Author:''|UdoBorkowski (ub [at] abego-software [dot] de)|
|''Licence:''|[[BSD open source license]]|
|''Macros:''|formTiddler, checkForDataTiddlerPlugin, newTiddlerWithForm|
|''Requires:''|DataTiddlerPlugin|
|''TiddlyWiki:''|1.2.38+, 2.0|
|''Browser:''|Firefox 1.0.4+; InternetExplorer 6.0|
!Description
Use form-based tiddlers to enter your tiddler data using text fields, listboxes, checkboxes etc. (All standard HTML Form input elements supported).
''Syntax:''
|>|{{{<<}}}''formTiddler'' //tiddlerName//{{{>>}}}|
|//tiddlerName//|The name of the FormTemplate tiddler to be used to edit the data of the tiddler containing the macro.|
|>|{{{<<}}}''newTiddlerWithForm'' //formTemplateName// //buttonLabel// [//titleExpression// [''askUser'']] {{{>>}}}|
|//formTemplateName//|The name of the tiddler that defines the form the new tiddler should use.|
|//buttonLabel//|The label of the button|
|//titleExpression//|A (quoted) JavaScript String expression that defines the title (/name) of the new tiddler.|
|''askUser''|Typically the user is not asked for the title when a title is specified (and not yet used). When ''askUser'' is given the user will be asked in any case. This may be used when the calculated title is just a suggestion that must be confirmed by the user|
|>|~~Syntax formatting: Keywords in ''bold'', optional parts in [...]. 'or' means that exactly one of the two alternatives must exist.~~|
For details and how to use the macros see the [[introduction|FormTiddler Introduction]] and the [[examples|FormTiddler Examples]].
!Revision history
* v1.0.6 (2007-06-24)
** Fixed problem when using SELECT component in Internet Explorer (thanks to MaikBoenig for reporting)
* v1.0.5 (2006-02-24)
** Removed "debugger;" instruction
* v1.0.4 (2006-02-07)
** Bug: On IE no data is written to data section when field values changed (thanks to KenGirard for reporting)
* v1.0.3 (2006-02-05)
** Bug: {{{"No form template specified in <<formTiddler>>"}}} when using formTiddler macro on InternetExplorer (thanks to KenGirard for reporting)
* v1.0.2 (2006-01-06)
** Support TiddlyWiki 2.0
* v1.0.1 (2005-12-22)
** Features:
*** Support InternetExplorer
*** Added newTiddlerWithForm Macro
* v1.0.0 (2005-12-14)
** initial version
!Code
***/
//{{{
//============================================================================
//============================================================================
// FormTiddlerPlugin
//============================================================================
//============================================================================
if (!window.abego) window.abego = {};
abego.getOptionsValue = function(element,i) {
var v = element.options[i].value;
if (!v && element.options[i].text)
v = element.options[i].text;
return v;
};
version.extensions.FormTiddlerPlugin = {
major: 1, minor: 0, revision: 5,
date: new Date(2006, 2, 24),
type: 'plugin',
source: "http://tiddlywiki.abego-software.de/#FormTiddlerPlugin"
};
// For backward compatibility with v1.2.x
//
if (!window.story) window.story=window;
if (!TiddlyWiki.prototype.getTiddler) TiddlyWiki.prototype.getTiddler = function(title) { return t = this.tiddlers[title]; return (t != undefined && t instanceof Tiddler) ? t : null; }
//============================================================================
// formTiddler Macro
//============================================================================
// -------------------------------------------------------------------------------
// Configurations and constants
// -------------------------------------------------------------------------------
config.macros.formTiddler = {
// Standard Properties
label: "formTiddler",
version: {major: 1, minor: 0, revision: 4, date: new Date(2006, 2, 7)},
prompt: "Edit tiddler data using forms",
// Define the "setters" that set the values of INPUT elements of a given type
// (must match the corresponding "getter")
setter: {
button: function(e, value) {/*contains no data */ },
checkbox: function(e, value) {e.checked = value;},
file: function(e, value) {try {e.value = value;} catch(e) {/* ignore, possibly security error*/}},
hidden: function(e, value) {e.value = value;},
password: function(e, value) {e.value = value;},
radio: function(e, value) {e.checked = (e.value == value);},
reset: function(e, value) {/*contains no data */ },
"select-one": function(e, value) {config.macros.formTiddler.setSelectOneValue(e,value);},
"select-multiple": function(e, value) {config.macros.formTiddler.setSelectMultipleValue(e,value);},
submit: function(e, value) {/*contains no data */},
text: function(e, value) {e.value = value;},
textarea: function(e, value) {e.value = value;}
},
// Define the "getters" that return the value of INPUT elements of a given type
// Return undefined to not store any data.
getter: {
button: function(e, value) {return undefined;},
checkbox: function(e, value) {return e.checked;},
file: function(e, value) {return e.value;},
hidden: function(e, value) {return e.value;},
password: function(e, value) {return e.value;},
radio: function(e, value) {return e.checked ? e.value : undefined;},
reset: function(e, value) {return undefined;},
"select-one": function(e, value) {return config.macros.formTiddler.getSelectOneValue(e);},
"select-multiple": function(e, value) {return config.macros.formTiddler.getSelectMultipleValue(e);},
submit: function(e, value) {return undefined;},
text: function(e, value) {return e.value;},
textarea: function(e, value) {return e.value;}
}
};
// -------------------------------------------------------------------------------
// The formTiddler Macro Handler
// -------------------------------------------------------------------------------
config.macros.formTiddler.handler = function(place,macroName,params,wikifier,paramString,tiddler) {
if (!config.macros.formTiddler.checkForExtensions(place, macroName)) {
return;
}
// --- Parsing ------------------------------------------
var i = 0; // index running over the params
// get the name of the form template tiddler
var formTemplateName = undefined;
if (i < params.length) {
formTemplateName = params[i];
i++;
}
if (!formTemplateName) {
config.macros.formTiddler.createErrorElement(place, "No form template specified in <<" + macroName + ">>.");
return;
}
// --- Processing ------------------------------------------
// Get the form template text.
// (This contains the INPUT elements for the form.)
var formTemplateTiddler = store.getTiddler(formTemplateName);
if (!formTemplateTiddler) {
config.macros.formTiddler.createErrorElement(place, "Form template '" + formTemplateName + "' not found.");
return;
}
var templateText = formTemplateTiddler.text;
if(!templateText) {
// Shortcut: when template text is empty we do nothing.
return;
}
// Get the name of the tiddler containing this "formTiddler" macro
// (i.e. the tiddler, that will be edited and that contains the data)
var tiddlerName = config.macros.formTiddler.getContainingTiddlerName(place);
// Append a "form" element.
var formName = "form"+formTemplateName+"__"+tiddlerName;
var e = document.createElement("form");
e.setAttribute("name", formName);
place.appendChild(e);
// "Embed" the elements defined by the templateText (i.e. the INPUT elements)
// into the "form" element we just created
wikify(templateText, e);
// Initialize the INPUT elements.
config.macros.formTiddler.initValuesAndHandlersInFormElements(formName, DataTiddler.getDataObject(tiddlerName));
}
// -------------------------------------------------------------------------------
// Form Data Access
// -------------------------------------------------------------------------------
// Internal.
//
// Initialize the INPUT elements of the form with the values of their "matching"
// data fields in the tiddler. Also setup the onChange handler to ensure that
// changes in the INPUT elements are stored in the tiddler's data.
//
config.macros.formTiddler.initValuesAndHandlersInFormElements = function(formName, data) {
// config.macros.formTiddler.trace("initValuesAndHandlersInFormElements(formName="+formName+", data="+data+")");
// find the form
var form = config.macros.formTiddler.findForm(formName);
if (!form) {
return;
}
try {
var elems = form.elements;
for (var i = 0; i < elems.length; i++) {
var c = elems[i];
var setter = config.macros.formTiddler.setter[c.type];
if (setter) {
var value = data[c.name];
if (value != null) {
setter(c, value);
}
c.onchange = onFormTiddlerChange;
} else {
config.macros.formTiddler.displayFormTiddlerError("No setter defined for INPUT element of type '"+c.type+"'. (Element '"+c.name+"' in form '"+formName+"')");
}
}
} catch(e) {
config.macros.formTiddler.displayFormTiddlerError("Error when updating elements with new formData. "+e);
}
}
// Internal.
//
// @return [may be null]
//
config.macros.formTiddler.findForm = function(formName) {
// We must manually iterate through the document's forms, since
// IE does not support the "document[formName]" approach
var forms = window.document.forms;
for (var i = 0; i < forms.length; i++) {
var form = forms[i];
if (form.name == formName) {
return form;
}
}
return null;
}
// Internal.
//
config.macros.formTiddler.setSelectOneValue = function(element,value) {
var n = element.options.length;
for (var i = 0; i < n; i++) {
element.options[i].selected = abego.getOptionsValue(element,i) == value;
}
}
// Internal.
//
config.macros.formTiddler.setSelectMultipleValue = function(element,value) {
var values = {};
for (var i = 0; i < value.length; i++) {
values[value[i]] = true;
}
var n = element.length;
for (var i = 0; i < n; i++) {
element.options[i].selected = !(!values[abego.getOptionsValue(element,i)]);
}
}
// Internal.
//
config.macros.formTiddler.getSelectOneValue = function(element) {
var i = element.selectedIndex;
return (i >= 0) ? abego.getOptionsValue(element,i) : null;
}
// Internal.
//
config.macros.formTiddler.getSelectMultipleValue = function(element) {
var values = [];
var n = element.length;
for (var i = 0; i < n; i++) {
if (element.options[i].selected) {
values.push(abego.getOptionsValue(element,i));
}
}
return values;
}
// -------------------------------------------------------------------------------
// Helpers
// -------------------------------------------------------------------------------
// Internal.
//
config.macros.formTiddler.checkForExtensions = function(place,macroName) {
if (!version.extensions.DataTiddlerPlugin) {
config.macros.formTiddler.createErrorElement(place, "<<" + macroName + ">> requires the DataTiddlerPlugin. (You can get it from http://tiddlywiki.abego-software.de/#DataTiddlerPlugin)");
return false;
}
return true;
}
// Internal.
//
// Displays a trace message in the "TiddlyWiki" message pane.
// (used for debugging)
//
config.macros.formTiddler.trace = function(s) {
displayMessage("Trace: "+s);
}
// Internal.
//
// Display some error message in the "TiddlyWiki" message pane.
//
config.macros.formTiddler.displayFormTiddlerError = function(s) {
alert("FormTiddlerPlugin Error: "+s);
}
// Internal.
//
// Creates an element that holds an error message
//
config.macros.formTiddler.createErrorElement = function(place, message) {
return createTiddlyElement(place,"span",null,"formTiddlerError",message);
}
// Internal.
//
// Returns the name of the tiddler containing the given element.
//
config.macros.formTiddler.getContainingTiddlerName = function(element) {
return story.findContainingTiddler(element).id.substr(7);
}
// -------------------------------------------------------------------------------
// Event Handlers
// -------------------------------------------------------------------------------
// This function must be called by the INPUT elements whenever their
// data changes. Typically this is done through an "onChange" handler.
//
function onFormTiddlerChange (e) {
// config.macros.formTiddler.trace("onFormTiddlerChange "+e);
if (!e) var e = window.event;
var target = resolveTarget(e);
var tiddlerName = config.macros.formTiddler.getContainingTiddlerName(target);
var getter = config.macros.formTiddler.getter[target.type];
if (getter) {
var value = getter(target);
DataTiddler.setData(tiddlerName, target.name, value);
} else {
config.macros.formTiddler.displayFormTiddlerError("No getter defined for INPUT element of type '"+target.type+"'. (Element '"+target.name+"' used in tiddler '"+tiddlerName+"')");
}
}
// ensure that the function can be used in HTML event handler
window.onFormTiddlerChange = onFormTiddlerChange;
// -------------------------------------------------------------------------------
// Stylesheet Extensions (may be overridden by local StyleSheet)
// -------------------------------------------------------------------------------
setStylesheet(
".formTiddlerError{color: #ffffff;background-color: #880000;}",
"formTiddler");
//============================================================================
// checkForDataTiddlerPlugin Macro
//============================================================================
config.macros.checkForDataTiddlerPlugin = {
// Standard Properties
label: "checkForDataTiddlerPlugin",
version: {major: 1, minor: 0, revision: 0, date: new Date(2005, 12, 14)},
prompt: "Check if the DataTiddlerPlugin exists"
}
config.macros.checkForDataTiddlerPlugin.handler = function(place,macroName,params) {
config.macros.formTiddler.checkForExtensions(place, config.macros.formTiddler.label);
}
//============================================================================
// newTiddlerWithForm Macro
//============================================================================
config.macros.newTiddlerWithForm = {
// Standard Properties
label: "newTiddlerWithForm",
version: {major: 1, minor: 0, revision: 1, date: new Date(2006, 1, 6)},
prompt: "Creates a new Tiddler with a <<formTiddler ...>> macro"
}
config.macros.newTiddlerWithForm.handler = function(place,macroName,params) {
// --- Parsing ------------------------------------------
var i = 0; // index running over the params
// get the name of the form template tiddler
var formTemplateName = undefined;
if (i < params.length) {
formTemplateName = params[i];
i++;
}
if (!formTemplateName) {
config.macros.formTiddler.createErrorElement(place, "No form template specified in <<" + macroName + ">>.");
return;
}
// get the button label
var buttonLabel = undefined;
if (i < params.length) {
buttonLabel = params[i];
i++;
}
if (!buttonLabel) {
config.macros.formTiddler.createErrorElement(place, "No button label specified in <<" + macroName + ">>.");
return;
}
// get the (optional) tiddlerName script and "askUser"
var tiddlerNameScript = undefined;
var askUser = false;
if (i < params.length) {
tiddlerNameScript = params[i];
i++;
if (i < params.length && params[i] == "askUser") {
askUser = true;
i++;
}
}
// --- Processing ------------------------------------------
if(!readOnly) {
var onClick = function() {
var tiddlerName;
if (tiddlerNameScript) {
try {
tiddlerName = eval(tiddlerNameScript);
} catch (ex) {
}
}
if (!tiddlerName || askUser) {
tiddlerName = prompt("Please specify a tiddler name.", askUser ? tiddlerName : "");
}
while (tiddlerName && store.getTiddler(tiddlerName)) {
tiddlerName = prompt("A tiddler named '"+tiddlerName+"' already exists.\n\n"+"Please specify a tiddler name.", tiddlerName);
}
// tiddlerName is either null (user canceled) or a name that is not yet in the store.
if (tiddlerName) {
var body = "<<formTiddler [["+formTemplateName+"]]>>";
var tags = [];
store.saveTiddler(tiddlerName,tiddlerName,body,config.options.txtUserName,new Date(),tags);
story.displayTiddler(null,tiddlerName,1);
}
}
createTiddlyButton(place,buttonLabel,buttonLabel,onClick);
}
}
//}}}
/***
!Licence and Copyright
Copyright (c) abego Software ~GmbH, 2005 ([[www.abego-software.de|http://www.abego-software.de]])
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 abego Software 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.
***/
/***
|Name|FullScreenPlugin|
|Created by|SaqImtiaz|
|Location|http://tw.lewcid.org/#FullScreenPlugin|
|Version|1.1|
|Requires|~TW2.x|
!Description:
Toggle between viewing tiddlers fullscreen and normally. Very handy for when you need more viewing space.
!Demo:
Click the ↕ button in the toolbar for this tiddler. Click it again to turn off fullscreen.
!Installation:
Copy the contents of this tiddler to your TW, tag with systemConfig, save and reload your TW.
Edit the ViewTemplate to add the fullscreen command to the toolbar.
!History:
*25-07-06: ver 1.1
*20-07-06: ver 1.0
!Code
***/
//{{{
var lewcidFullScreen = false;
config.commands.fullscreen =
{
text:" ↕ ",
tooltip:"Fullscreen mode"
};
config.commands.fullscreen.handler = function (event,src,title)
{
if (lewcidFullScreen == false)
{
lewcidFullScreen = true;
setStylesheet('#sidebar, .header, #mainMenu{display:none;} #displayArea{margin:0em 0 0 0 !important;}',"lewcidFullScreenStyle");
}
else
{
lewcidFullScreen = false;
setStylesheet(' ',"lewcidFullScreenStyle");
}
}
config.macros.fullscreen={};
config.macros.fullscreen.handler = function(place,macroName,params,wikifier,paramString,tiddler)
{
var label = params[0]||" ↕ ";
var tooltip = params[1]||"Fullscreen mode";
createTiddlyButton(place,label,tooltip,config.commands.fullscreen.handler);
}
var lewcid_fullscreen_closeTiddler = Story.prototype.closeTiddler;
Story.prototype.closeTiddler =function(title,animate,slowly)
{
lewcid_fullscreen_closeTiddler.apply(this,arguments);
if (story.isEmpty() && lewcidFullScreen == true)
config.commands.fullscreen.handler();
}
Slider.prototype.lewcidStop = Slider.prototype.stop;
Slider.prototype.stop = function()
{
this.lewcidStop();
if (story.isEmpty() && lewcidFullScreen == true)
config.commands.fullscreen.handler();
}
//}}}
/***
|Name:|HideWhenPlugin|
|Description:|Allows conditional inclusion/exclusion in templates|
|Version:|3.1 ($Rev: 3919 $)|
|Date:|$Date: 2008-03-13 02:03:12 +1000 (Thu, 13 Mar 2008) $|
|Source:|http://mptw.tiddlyspot.com/#HideWhenPlugin|
|Author:|Simon Baird <simon.baird@gmail.com>|
|License:|http://mptw.tiddlyspot.com/#TheBSDLicense|
For use in ViewTemplate and EditTemplate. Example usage:
{{{<div macro="showWhenTagged Task">[[TaskToolbar]]</div>}}}
{{{<div macro="showWhen tiddler.modifier == 'BartSimpson'"><img src="bart.gif"/></div>}}}
***/
//{{{
window.hideWhenLastTest = false;
window.removeElementWhen = function(test,place) {
window.hideWhenLastTest = test;
if (test) {
removeChildren(place);
place.parentNode.removeChild(place);
}
};
merge(config.macros,{
hideWhen: { handler: function(place,macroName,params,wikifier,paramString,tiddler) {
removeElementWhen( eval(paramString), place);
}},
showWhen: { handler: function(place,macroName,params,wikifier,paramString,tiddler) {
removeElementWhen( !eval(paramString), place);
}},
hideWhenTagged: { handler: function (place,macroName,params,wikifier,paramString,tiddler) {
removeElementWhen( tiddler.tags.containsAll(params), place);
}},
showWhenTagged: { handler: function (place,macroName,params,wikifier,paramString,tiddler) {
removeElementWhen( !tiddler.tags.containsAll(params), place);
}},
hideWhenTaggedAny: { handler: function (place,macroName,params,wikifier,paramString,tiddler) {
removeElementWhen( tiddler.tags.containsAny(params), place);
}},
showWhenTaggedAny: { handler: function (place,macroName,params,wikifier,paramString,tiddler) {
removeElementWhen( !tiddler.tags.containsAny(params), place);
}},
hideWhenTaggedAll: { handler: function (place,macroName,params,wikifier,paramString,tiddler) {
removeElementWhen( tiddler.tags.containsAll(params), place);
}},
showWhenTaggedAll: { handler: function (place,macroName,params,wikifier,paramString,tiddler) {
removeElementWhen( !tiddler.tags.containsAll(params), place);
}},
hideWhenExists: { handler: function(place,macroName,params,wikifier,paramString,tiddler) {
removeElementWhen( store.tiddlerExists(params[0]) || store.isShadowTiddler(params[0]), place);
}},
showWhenExists: { handler: function(place,macroName,params,wikifier,paramString,tiddler) {
removeElementWhen( !(store.tiddlerExists(params[0]) || store.isShadowTiddler(params[0])), place);
}},
hideWhenTitleIs: { handler: function(place,macroName,params,wikifier,paramString,tiddler) {
removeElementWhen( tiddler.title == params[0], place);
}},
showWhenTitleIs: { handler: function(place,macroName,params,wikifier,paramString,tiddler) {
removeElementWhen( tiddler.title != params[0], place);
}},
'else': { handler: function(place,macroName,params,wikifier,paramString,tiddler) {
removeElementWhen( !window.hideWhenLastTest, place);
}}
});
//}}}
Nel paradosso esposto da Zeno intorno al 450 a.C., una tartaruga sfida Achille in una corsa. Achille era conosciuto per essere un velocista. La tartaruga però sostiene di poter vincere se viene fatta partire in vantaggio dato che Achille non può riuscire a raggiungerla.
Com'é possibile ciò?
/***
|Name|InlineJavascriptPlugin|
|Source|http://www.TiddlyTools.com/#InlineJavascriptPlugin|
|Version|1.6.0|
|Author|Eric Shulman - ELS Design Studios|
|License|http://www.TiddlyTools.com/#LegalStatements <<br>>and [[Creative Commons Attribution-ShareAlike 2.5 License|http://creativecommons.org/licenses/by-sa/2.5/]]|
|~CoreVersion|2.1|
|Type|plugin|
|Requires||
|Overrides||
|Description|Insert Javascript executable code directly into your tiddler content.|
''Call directly into TW core utility routines, define new functions, calculate values, add dynamically-generated TiddlyWiki-formatted output'' into tiddler content, or perform any other programmatic actions each time the tiddler is rendered.
!!!!!Usage
<<<
When installed, this plugin adds new wiki syntax for surrounding tiddler content with {{{<script>}}} and {{{</script>}}} markers, so that it can be treated as embedded javascript and executed each time the tiddler is rendered.
''Deferred execution from an 'onClick' link''
By including a {{{label="..."}}} parameter in the initial {{{<script>}}} marker, the plugin will create a link to an 'onclick' script that will only be executed when that specific link is clicked, rather than running the script each time the tiddler is rendered. You may also include a {{{title="..."}}} parameter to specify the 'tooltip' text that will appear whenever the mouse is moved over the onClick link text
''External script source files:''
You can also load javascript from an external source URL, by including a src="..." parameter in the initial {{{<script>}}} marker (e.g., {{{<script src="demo.js"></script>}}}). This is particularly useful when incorporating third-party javascript libraries for use in custom extensions and plugins. The 'foreign' javascript code remains isolated in a separate file that can be easily replaced whenever an updated library file becomes available.
''Display script source in tiddler output''
By including the keyword parameter "show", in the initial {{{<script>}}} marker, the plugin will include the script source code in the output that it displays in the tiddler.
''Defining javascript functions and libraries:''
Although the external javascript file is loaded while the tiddler content is being rendered, any functions it defines will not be available for use until //after// the rendering has been completed. Thus, you cannot load a library and //immediately// use it's functions within the same tiddler. However, once that tiddler has been loaded, the library functions can be freely used in any tiddler (even the one in which it was initially loaded).
To ensure that your javascript functions are always available when needed, you should load the libraries from a tiddler that will be rendered as soon as your TiddlyWiki document is opened. For example, you could put your {{{<script src="..."></script>}}} syntax into a tiddler called LoadScripts, and then add {{{<<tiddler LoadScripts>>}}} in your MainMenu tiddler.
Since the MainMenu is always rendered immediately upon opening your document, the library will always be loaded before any other tiddlers that rely upon the functions it defines. Loading an external javascript library does not produce any direct output in the tiddler, so these definitions should have no impact on the appearance of your MainMenu.
''Creating dynamic tiddler content''
An important difference between this implementation of embedded scripting and conventional embedded javascript techniques for web pages is the method used to produce output that is dynamically inserted into the document:
* In a typical web document, you use the document.write() function to output text sequences (often containing HTML tags) that are then rendered when the entire document is first loaded into the browser window.
* However, in a ~TiddlyWiki document, tiddlers (and other DOM elements) are created, deleted, and rendered "on-the-fly", so writing directly to the global 'document' object does not produce the results you want (i.e., replacing the embedded script within the tiddler content), and completely replaces the entire ~TiddlyWiki document in your browser window.
* To allow these scripts to work unmodified, the plugin automatically converts all occurences of document.write() so that the output is inserted into the tiddler content instead of replacing the entire ~TiddlyWiki document.
If your script does not use document.write() to create dynamically embedded content within a tiddler, your javascript can, as an alternative, explicitly return a text value that the plugin can then pass through the wikify() rendering engine to insert into the tiddler display. For example, using {{{return "thistext"}}} will produce the same output as {{{document.write("thistext")}}}.
//Note: your script code is automatically 'wrapped' inside a function, {{{_out()}}}, so that any return value you provide can be correctly handled by the plugin and inserted into the tiddler. To avoid unpredictable results (and possibly fatal execution errors), this function should never be redefined or called from ''within'' your script code.//
''Accessing the ~TiddlyWiki DOM''
The plugin provides one pre-defined variable, 'place', that is passed in to your javascript code so that it can have direct access to the containing DOM element into which the tiddler output is currently being rendered.
Access to this DOM element allows you to create scripts that can:
* vary their actions based upon the specific location in which they are embedded
* access 'tiddler-relative' information (use findContainingTiddler(place))
* perform direct DOM manipulations (when returning wikified text is not enough)
<<<
!!!!!Examples
<<<
an "alert" message box:
><script show>
alert('InlineJavascriptPlugin: this is a demonstration message');
</script>
dynamic output:
><script show>
return (new Date()).toString();
</script>
wikified dynamic output:
><script show>
return "link to current user: [["+config.options.txtUserName+"]]";
</script>
dynamic output using 'place' to get size information for current tiddler:
><script show>
if (!window.story) window.story=window;
var title=story.findContainingTiddler(place).id.substr(7);
return title+" is using "+store.getTiddlerText(title).length+" bytes";
</script>
creating an 'onclick' button/link that runs a script:
><script label="click here" title="clicking this link will show an 'alert' box" show>
if (!window.story) window.story=window;
alert("Hello World!\nlinktext='"+place.firstChild.data+"'\ntiddler='"+story.findContainingTiddler(place).id.substr(7)+"'");
</script>
loading a script from a source url:
>http://www.TiddlyTools.com/demo.js contains:
>>{{{function demo() { alert('this output is from demo(), defined in demo.js') } }}}
>>{{{alert('InlineJavascriptPlugin: demo.js has been loaded'); }}}
><script src="demo.js" show>
return "loading demo.js..."
</script>
><script label="click to execute demo() function" show>
demo()
</script>
<<<
!!!!!Installation
<<<
import (or copy/paste) the following tiddlers into your document:
''InlineJavascriptPlugin'' (tagged with <<tag systemConfig>>)
<<<
!!!!!Revision History
<<<
''2007.02.19 [1.6.0]'' added support for title="..." to specify mouseover tooltip when using an onclick (label="...") script
''2006.10.16 [1.5.2]'' add newline before closing '}' in 'function out_' wrapper. Fixes error caused when last line of script is a comment.
''2006.06.01 [1.5.1]'' when calling wikify() on script return value, pass hightlightRegExp and tiddler params so macros that rely on these values can render properly
''2006.04.19 [1.5.0]'' added 'show' parameter to force display of javascript source code in tiddler output
''2006.01.05 [1.4.0]'' added support 'onclick' scripts. When label="..." param is present, a button/link is created using the indicated label text, and the script is only executed when the button/link is clicked. 'place' value is set to match the clicked button/link element.
''2005.12.13 [1.3.1]'' when catching eval error in IE, e.description contains the error text, instead of e.toString(). Fixed error reporting so IE shows the correct response text. Based on a suggestion by UdoBorkowski
''2005.11.09 [1.3.0]'' for 'inline' scripts (i.e., not scripts loaded with src="..."), automatically replace calls to 'document.write()' with 'place.innerHTML+=' so script output is directed into tiddler content. Based on a suggestion by BradleyMeck
''2005.11.08 [1.2.0]'' handle loading of javascript from an external URL via src="..." syntax
''2005.11.08 [1.1.0]'' pass 'place' param into scripts to provide direct DOM access
''2005.11.08 [1.0.0]'' initial release
<<<
!!!!!Credits
<<<
This feature was developed by EricShulman from [[ELS Design Studios|http:/www.elsdesign.com]]
<<<
!!!!!Code
***/
//{{{
version.extensions.inlineJavascript= {major: 1, minor: 6, revision: 0, date: new Date(2007,2,19)};
config.formatters.push( {
name: "inlineJavascript",
match: "\\<script",
lookahead: "\\<script(?: src=\\\"((?:.|\\n)*?)\\\")?(?: label=\\\"((?:.|\\n)*?)\\\")?(?: title=\\\"((?:.|\\n)*?)\\\")?( show)?\\>((?:.|\\n)*?)\\</script\\>",
handler: function(w) {
var lookaheadRegExp = new RegExp(this.lookahead,"mg");
lookaheadRegExp.lastIndex = w.matchStart;
var lookaheadMatch = lookaheadRegExp.exec(w.source)
if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {
if (lookaheadMatch[1]) { // load a script library
// make script tag, set src, add to body to execute, then remove for cleanup
var script = document.createElement("script"); script.src = lookaheadMatch[1];
document.body.appendChild(script); document.body.removeChild(script);
}
if (lookaheadMatch[5]) { // there is script code
if (lookaheadMatch[4]) // show inline script code in tiddler output
wikify("{{{\n"+lookaheadMatch[0]+"\n}}}\n",w.output);
if (lookaheadMatch[2]) { // create a link to an 'onclick' script
// add a link, define click handler, save code in link (pass 'place'), set link attributes
var link=createTiddlyElement(w.output,"a",null,"tiddlyLinkExisting",lookaheadMatch[2]);
link.onclick=function(){try{return(eval(this.code))}catch(e){alert(e.description?e.description:e.toString())}}
link.code="function _out(place){"+lookaheadMatch[5]+"\n};_out(this);"
link.setAttribute("title",lookaheadMatch[3]?lookaheadMatch[3]:"");
link.setAttribute("href","javascript:;");
link.style.cursor="pointer";
}
else { // run inline script code
var code="function _out(place){"+lookaheadMatch[5]+"\n};_out(w.output);"
code=code.replace(/document.write\(/gi,'place.innerHTML+=(');
try { var out = eval(code); } catch(e) { out = e.description?e.description:e.toString(); }
if (out && out.length) wikify(out,w.output,w.highlightRegExp,w.tiddler);
}
}
w.nextMatch = lookaheadMatch.index + lookaheadMatch[0].length;
}
}
} )
//}}}
/***
|''Name:''|LaTeXMathMLPlugin|
|''Description:''|~LaTeX plugin with ~MathML output based on [[LaTeXMathML|http://www.maths.nottingham.ac.uk/personal/drw/lm.html]]|
|''Version:''|1.1|
|''Date:''|Oct 06, 2007|
|''Source:''|http://www.math.ist.utl.pt/~psoares/addons.html|
|''Documentation:''|[[LaTeXMathMLPlugin Documentation|LaTeXMathMLPluginDoc]]|
|''Author:''|Paulo Soares|
|''License:''|[[Creative Commons Attribution-Share Alike 3.0 License|http://creativecommons.org/licenses/by-sa/3.0/]]|
|''~CoreVersion:''|2.1.0|
***/
//{{{
config.macros.LaTeXMathMLPlugin = {
AMnames: [],
isIE: document.createElementNS==null,
AMmathml: "http://www.w3.org/1998/Math/MathML",
AMcal: [0xEF35,0x212C,0xEF36,0xEF37,0x2130,0x2131,0xEF38,0x210B,0x2110,0xEF39,0xEF3A,0x2112,0x2133,0xEF3B,0xEF3C,0xEF3D,0xEF3E,0x211B,0xEF3F,0xEF40,0xEF41,0xEF42,0xEF43,0xEF44,0xEF45,0xEF46],
AMfrk: [0xEF5D,0xEF5E,0x212D,0xEF5F,0xEF60,0xEF61,0xEF62,0x210C,0x2111,0xEF63,0xEF64,0xEF65,0xEF66,0xEF67,0xEF68,0xEF69,0xEF6A,0x211C,0xEF6B,0xEF6C,0xEF6D,0xEF6E,0xEF6F,0xEF70,0xEF71,0x2128],
AMbbb: [0xEF8C,0xEF8D,0x2102,0xEF8E,0xEF8F,0xEF90,0xEF91,0x210D,0xEF92,0xEF93,0xEF94,0xEF95,0xEF96,0x2115,0xEF97,0x2119,0x211A,0x211D,0xEF98,0xEF99,0xEF9A,0xEF9B,0xEF9C,0xEF9D,0xEF9E,0x2124],
CONST: 0, UNARY: 1, BINARY: 2, INFIX: 3, LEFTBRACKET: 4, RIGHTBRACKET: 5, SPACE: 6, UNDEROVER: 7, DEFINITION: 8, TEXT: 9, BIG: 10, LONG: 11, STRETCHY: 12, MATRIX: 13,
AMsymbols: [
//Greek letters
{input:"\\alpha", tag:"mi", output:"\u03B1", ttype:0},
{input:"\\beta", tag:"mi", output:"\u03B2", ttype:0},
{input:"\\gamma", tag:"mi", output:"\u03B3", ttype:0},
{input:"\\delta", tag:"mi", output:"\u03B4", ttype:0},
{input:"\\epsilon", tag:"mi", output:"\u03B5", ttype:0},
{input:"\\varepsilon", tag:"mi", output:"\u025B", ttype:0},
{input:"\\zeta", tag:"mi", output:"\u03B6", ttype:0},
{input:"\\eta", tag:"mi", output:"\u03B7", ttype:0},
{input:"\\theta", tag:"mi", output:"\u03B8", ttype:0},
{input:"\\vartheta", tag:"mi", output:"\u03D1", ttype:0},
{input:"\\iota", tag:"mi", output:"\u03B9", ttype:0},
{input:"\\kappa", tag:"mi", output:"\u03BA", ttype:0},
{input:"\\lambda", tag:"mi", output:"\u03BB", ttype:0},
{input:"\\mu", tag:"mi", output:"\u03BC", ttype:0},
{input:"\\nu", tag:"mi", output:"\u03BD", ttype:0},
{input:"\\xi", tag:"mi", output:"\u03BE", ttype:0},
{input:"\\pi", tag:"mi", output:"\u03C0", ttype:0},
{input:"\\varpi", tag:"mi", output:"\u03D6", ttype:0},
{input:"\\rho", tag:"mi", output:"\u03C1", ttype:0},
{input:"\\varrho", tag:"mi", output:"\u03F1", ttype:0},
{input:"\\varsigma", tag:"mi", output:"\u03C2", ttype:0},
{input:"\\sigma", tag:"mi", output:"\u03C3", ttype:0},
{input:"\\tau", tag:"mi", output:"\u03C4", ttype:0},
{input:"\\upsilon", tag:"mi", output:"\u03C5", ttype:0},
{input:"\\phi", tag:"mi", output:"\u03C6", ttype:0},
{input:"\\varphi", tag:"mi", output:"\u03D5", ttype:0},
{input:"\\chi", tag:"mi", output:"\u03C7", ttype:0},
{input:"\\psi", tag:"mi", output:"\u03C8", ttype:0},
{input:"\\omega", tag:"mi", output:"\u03C9", ttype:0},
{input:"\\Gamma", tag:"mo", output:"\u0393", ttype:0},
{input:"\\Delta", tag:"mo", output:"\u0394", ttype:0},
{input:"\\Theta", tag:"mo", output:"\u0398", ttype:0},
{input:"\\Lambda", tag:"mo", output:"\u039B", ttype:0},
{input:"\\Xi", tag:"mo", output:"\u039E", ttype:0},
{input:"\\Pi", tag:"mo", output:"\u03A0", ttype:0},
{input:"\\Sigma", tag:"mo", output:"\u03A3", ttype:0},
{input:"\\Upsilon", tag:"mo", output:"\u03A5", ttype:0},
{input:"\\Phi", tag:"mo", output:"\u03A6", ttype:0},
{input:"\\Psi", tag:"mo", output:"\u03A8", ttype:0},
{input:"\\Omega", tag:"mo", output:"\u03A9", ttype:0},
//fractions
{input:"\\frac12", tag:"mo", output:"\u00BD", ttype:0},
{input:"\\frac14", tag:"mo", output:"\u00BC", ttype:0},
{input:"\\frac34", tag:"mo", output:"\u00BE", ttype:0},
{input:"\\frac13", tag:"mo", output:"\u2153", ttype:0},
{input:"\\frac23", tag:"mo", output:"\u2154", ttype:0},
{input:"\\frac15", tag:"mo", output:"\u2155", ttype:0},
{input:"\\frac25", tag:"mo", output:"\u2156", ttype:0},
{input:"\\frac35", tag:"mo", output:"\u2157", ttype:0},
{input:"\\frac45", tag:"mo", output:"\u2158", ttype:0},
{input:"\\frac16", tag:"mo", output:"\u2159", ttype:0},
{input:"\\frac56", tag:"mo", output:"\u215A", ttype:0},
{input:"\\frac18", tag:"mo", output:"\u215B", ttype:0},
{input:"\\frac38", tag:"mo", output:"\u215C", ttype:0},
{input:"\\frac58", tag:"mo", output:"\u215D", ttype:0},
{input:"\\frac78", tag:"mo", output:"\u215E", ttype:0},
//binary operation symbols
{input:"\\pm", tag:"mo", output:"\u00B1", ttype:0},
{input:"\\mp", tag:"mo", output:"\u2213", ttype:0},
{input:"\\triangleleft",tag:"mo", output:"\u22B2", ttype:0},
{input:"\\triangleright",tag:"mo",output:"\u22B3", ttype:0},
{input:"\\cdot", tag:"mo", output:"\u22C5", ttype:0},
{input:"\\star", tag:"mo", output:"\u22C6", ttype:0},
{input:"\\ast", tag:"mo", output:"\u002A", ttype:0},
{input:"\\times", tag:"mo", output:"\u00D7", ttype:0},
{input:"\\div", tag:"mo", output:"\u00F7", ttype:0},
{input:"\\circ", tag:"mo", output:"\u2218", ttype:0},
{input:"\\bullet", tag:"mo", output:"\u2022", ttype:0},
{input:"\\oplus", tag:"mo", output:"\u2295", ttype:0},
{input:"\\ominus", tag:"mo", output:"\u2296", ttype:0},
{input:"\\otimes", tag:"mo", output:"\u2297", ttype:0},
{input:"\\bigcirc", tag:"mo", output:"\u25CB", ttype:0},
{input:"\\oslash", tag:"mo", output:"\u2298", ttype:0},
{input:"\\odot", tag:"mo", output:"\u2299", ttype:0},
{input:"\\land", tag:"mo", output:"\u2227", ttype:0},
{input:"\\wedge", tag:"mo", output:"\u2227", ttype:0},
{input:"\\lor", tag:"mo", output:"\u2228", ttype:0},
{input:"\\vee", tag:"mo", output:"\u2228", ttype:0},
{input:"\\cap", tag:"mo", output:"\u2229", ttype:0},
{input:"\\cup", tag:"mo", output:"\u222A", ttype:0},
{input:"\\sqcap", tag:"mo", output:"\u2293", ttype:0},
{input:"\\sqcup", tag:"mo", output:"\u2294", ttype:0},
{input:"\\uplus", tag:"mo", output:"\u228E", ttype:0},
{input:"\\amalg", tag:"mo", output:"\u2210", ttype:0},
{input:"\\bigtriangleup",tag:"mo",output:"\u25B3", ttype:0},
{input:"\\bigtriangledown",tag:"mo",output:"\u25BD", ttype:0},
{input:"\\dag", tag:"mo", output:"\u2020", ttype:0},
{input:"\\dagger", tag:"mo", output:"\u2020", ttype:0},
{input:"\\ddag", tag:"mo", output:"\u2021", ttype:0},
{input:"\\ddagger", tag:"mo", output:"\u2021", ttype:0},
{input:"\\lhd", tag:"mo", output:"\u22B2", ttype:0},
{input:"\\rhd", tag:"mo", output:"\u22B3", ttype:0},
{input:"\\unlhd", tag:"mo", output:"\u22B4", ttype:0},
{input:"\\unrhd", tag:"mo", output:"\u22B5", ttype:0},
//Big Operators
{input:"\\sum", tag:"mo", output:"\u2211", ttype:7},
{input:"\\prod", tag:"mo", output:"\u220F", ttype:7},
{input:"\\bigcap", tag:"mo", output:"\u22C2", ttype:7},
{input:"\\bigcup", tag:"mo", output:"\u22C3", ttype:7},
{input:"\\bigwedge", tag:"mo", output:"\u22C0", ttype:7},
{input:"\\bigvee", tag:"mo", output:"\u22C1", ttype:7},
{input:"\\bigsqcap", tag:"mo", output:"\u2A05", ttype:7},
{input:"\\bigsqcup", tag:"mo", output:"\u2A06", ttype:7},
{input:"\\coprod", tag:"mo", output:"\u2210", ttype:7},
{input:"\\bigoplus", tag:"mo", output:"\u2A01", ttype:7},
{input:"\\bigotimes", tag:"mo", output:"\u2A02", ttype:7},
{input:"\\bigodot", tag:"mo", output:"\u2A00", ttype:7},
{input:"\\biguplus", tag:"mo", output:"\u2A04", ttype:7},
{input:"\\int", tag:"mo", output:"\u222B", ttype:0},
{input:"\\oint", tag:"mo", output:"\u222E", ttype:0},
//binary relation symbols
{input:":=", tag:"mo", output:":=", ttype:0},
{input:"\\lt", tag:"mo", output:"<", ttype:0},
{input:"\\gt", tag:"mo", output:">", ttype:0},
{input:"\\ne", tag:"mo", output:"\u2260", ttype:0},
{input:"\\neq", tag:"mo", output:"\u2260", ttype:0},
{input:"\\le", tag:"mo", output:"\u2264", ttype:0},
{input:"\\leq", tag:"mo", output:"\u2264", ttype:0},
{input:"\\leqslant", tag:"mo", output:"\u2264", ttype:0},
{input:"\\ge", tag:"mo", output:"\u2265", ttype:0},
{input:"\\geq", tag:"mo", output:"\u2265", ttype:0},
{input:"\\geqslant", tag:"mo", output:"\u2265", ttype:0},
{input:"\\equiv", tag:"mo", output:"\u2261", ttype:0},
{input:"\\ll", tag:"mo", output:"\u226A", ttype:0},
{input:"\\gg", tag:"mo", output:"\u226B", ttype:0},
{input:"\\doteq", tag:"mo", output:"\u2250", ttype:0},
{input:"\\prec", tag:"mo", output:"\u227A", ttype:0},
{input:"\\succ", tag:"mo", output:"\u227B", ttype:0},
{input:"\\preceq", tag:"mo", output:"\u227C", ttype:0},
{input:"\\succeq", tag:"mo", output:"\u227D", ttype:0},
{input:"\\subset", tag:"mo", output:"\u2282", ttype:0},
{input:"\\supset", tag:"mo", output:"\u2283", ttype:0},
{input:"\\subseteq", tag:"mo", output:"\u2286", ttype:0},
{input:"\\supseteq", tag:"mo", output:"\u2287", ttype:0},
{input:"\\sqsubset", tag:"mo", output:"\u228F", ttype:0},
{input:"\\sqsupset", tag:"mo", output:"\u2290", ttype:0},
{input:"\\sqsubseteq", tag:"mo", output:"\u2291", ttype:0},
{input:"\\sqsupseteq", tag:"mo", output:"\u2292", ttype:0},
{input:"\\sim", tag:"mo", output:"\u223C", ttype:0},
{input:"\\simeq", tag:"mo", output:"\u2243", ttype:0},
{input:"\\approx", tag:"mo", output:"\u2248", ttype:0},
{input:"\\cong", tag:"mo", output:"\u2245", ttype:0},
{input:"\\Join", tag:"mo", output:"\u22C8", ttype:0},
{input:"\\bowtie", tag:"mo", output:"\u22C8", ttype:0},
{input:"\\in", tag:"mo", output:"\u2208", ttype:0},
{input:"\\ni", tag:"mo", output:"\u220B", ttype:0},
{input:"\\owns", tag:"mo", output:"\u220B", ttype:0},
{input:"\\propto", tag:"mo", output:"\u221D", ttype:0},
{input:"\\vdash", tag:"mo", output:"\u22A2", ttype:0},
{input:"\\dashv", tag:"mo", output:"\u22A3", ttype:0},
{input:"\\models", tag:"mo", output:"\u22A8", ttype:0},
{input:"\\perp", tag:"mo", output:"\u22A5", ttype:0},
{input:"\\smile", tag:"mo", output:"\u2323", ttype:0},
{input:"\\frown", tag:"mo", output:"\u2322", ttype:0},
{input:"\\asymp", tag:"mo", output:"\u224D", ttype:0},
{input:"\\notin", tag:"mo", output:"\u2209", ttype:0},
//matrices
{input:"\\begin{eqnarray}", output:"X", ttype:13, invisible:true},
{input:"\\begin{array}", output:"X", ttype:13, invisible:true},
{input:"\\\\", output:"}&{", ttype:8},
{input:"\\end{eqnarray}", output:"}}", ttype:8},
{input:"\\end{array}", output:"}}", ttype:8},
//grouping and literal brackets -- ieval is for IE
{input:"\\big", tag:"mo", output:"X", atval:"1.2", ieval:"2.2", ttype:10},
{input:"\\Big", tag:"mo", output:"X", atval:"1.6", ieval:"2.6", ttype:10},
{input:"\\bigg", tag:"mo", output:"X", atval:"2.2", ieval:"3.2", ttype:10},
{input:"\\Bigg", tag:"mo", output:"X", atval:"2.9", ieval:"3.9", ttype:10},
{input:"\\left", tag:"mo", output:"X", ttype:4},
{input:"\\right", tag:"mo", output:"X", ttype:5},
{input:"{", output:"{", ttype:4, invisible:true},
{input:"}", output:"}", ttype:5, invisible:true},
{input:"(", tag:"mo", output:"(", atval:"1", ttype:12},
{input:"[", tag:"mo", output:"[", atval:"1", ttype:12},
{input:"\\lbrack", tag:"mo", output:"[", atval:"1", ttype:12},
{input:"\\{", tag:"mo", output:"{", atval:"1", ttype:12},
{input:"\\lbrace", tag:"mo", output:"{", atval:"1", ttype:12},
{input:"\\langle", tag:"mo", output:"\u2329", atval:"1", ttype:12},
{input:"\\lfloor", tag:"mo", output:"\u230A", atval:"1", ttype:12},
{input:"\\lceil", tag:"mo", output:"\u2308", atval:"1", ttype:12},
// rtag:"mi" causes space to be inserted before a following sin, cos, etc.
// (see function AMparseExpr() )
{input:")", tag:"mo",output:")", rtag:"mi",atval:"1",ttype:12},
{input:"]", tag:"mo",output:"]", rtag:"mi",atval:"1",ttype:12},
{input:"\\rbrack",tag:"mo",output:"]", rtag:"mi",atval:"1",ttype:12},
{input:"\\}", tag:"mo",output:"}", rtag:"mi",atval:"1",ttype:12},
{input:"\\rbrace",tag:"mo",output:"}", rtag:"mi",atval:"1",ttype:12},
{input:"\\rangle",tag:"mo",output:"\u232A", rtag:"mi",atval:"1",ttype:12},
{input:"\\rfloor",tag:"mo",output:"\u230B", rtag:"mi",atval:"1",ttype:12},
{input:"\\rceil", tag:"mo",output:"\u2309", rtag:"mi",atval:"1",ttype:12},
// "|", "\\|", "\\vert" and "\\Vert" modified later: lspace = rspace = 0em
{input:"|", tag:"mo", output:"\u2223", atval:"1", ttype:12},
{input:"\\|", tag:"mo", output:"\u2225", atval:"1", ttype:12},
{input:"\\vert", tag:"mo", output:"\u2223", atval:"1", ttype:12},
{input:"\\Vert", tag:"mo", output:"\u2225", atval:"1", ttype:12},
{input:"\\mid", tag:"mo", output:"\u2223", atval:"1", ttype:12},
{input:"\\parallel", tag:"mo", output:"\u2225", atval:"1", ttype:12},
{input:"/", tag:"mo", output:"/", atval:"1.01", ttype:12},
{input:"\\backslash", tag:"mo", output:"\u2216", atval:"1", ttype:12},
{input:"\\setminus", tag:"mo", output:"\\", ttype:0},
//miscellaneous symbols
{input:"\\!", tag:"mspace", atname:"width", atval:"-0.167em", ttype:6},
{input:"\\,", tag:"mspace", atname:"width", atval:"0.167em", ttype:6},
{input:"\\>", tag:"mspace", atname:"width", atval:"0.222em", ttype:6},
{input:"\\:", tag:"mspace", atname:"width", atval:"0.222em", ttype:6},
{input:"\\;", tag:"mspace", atname:"width", atval:"0.278em", ttype:6},
{input:"~", tag:"mspace", atname:"width", atval:"0.333em", ttype:6},
{input:"\\quad", tag:"mspace", atname:"width", atval:"1em", ttype:6},
{input:"\\qquad", tag:"mspace", atname:"width", atval:"2em", ttype:6},
{input:"\\prime", tag:"mo", output:"\u2032", ttype:0},
{input:"'", tag:"mo", output:"\u02B9", ttype:0},
{input:"''", tag:"mo", output:"\u02BA", ttype:0},
{input:"'''", tag:"mo", output:"\u2034", ttype:0},
{input:"''''", tag:"mo", output:"\u2057", ttype:0},
{input:"\\ldots", tag:"mo", output:"\u2026", ttype:0},
{input:"\\cdots", tag:"mo", output:"\u22EF", ttype:0},
{input:"\\vdots", tag:"mo", output:"\u22EE", ttype:0},
{input:"\\ddots", tag:"mo", output:"\u22F1", ttype:0},
{input:"\\forall", tag:"mo", output:"\u2200", ttype:0},
{input:"\\exists", tag:"mo", output:"\u2203", ttype:0},
{input:"\\Re", tag:"mo", output:"\u211C", ttype:0},
{input:"\\Im", tag:"mo", output:"\u2111", ttype:0},
{input:"\\aleph", tag:"mo", output:"\u2135", ttype:0},
{input:"\\hbar", tag:"mo", output:"\u210F", ttype:0},
{input:"\\ell", tag:"mo", output:"\u2113", ttype:0},
{input:"\\wp", tag:"mo", output:"\u2118", ttype:0},
{input:"\\emptyset", tag:"mo", output:"\u2205", ttype:0},
{input:"\\infty", tag:"mo", output:"\u221E", ttype:0},
{input:"\\surd", tag:"mo", output:"\\sqrt{}", ttype:8},
{input:"\\partial", tag:"mo", output:"\u2202", ttype:0},
{input:"\\nabla", tag:"mo", output:"\u2207", ttype:0},
{input:"\\triangle", tag:"mo", output:"\u25B3", ttype:0},
{input:"\\therefore", tag:"mo", output:"\u2234", ttype:0},
{input:"\\angle", tag:"mo", output:"\u2220", ttype:0},
{input:"\\diamond", tag:"mo", output:"\u22C4", ttype:0},
{input:"\\Diamond", tag:"mo", output:"\u25C7", ttype:0},
{input:"\\neg", tag:"mo", output:"\u00AC", ttype:0},
{input:"\\lnot", tag:"mo", output:"\u00AC", ttype:0},
{input:"\\bot", tag:"mo", output:"\u22A5", ttype:0},
{input:"\\top", tag:"mo", output:"\u22A4", ttype:0},
{input:"\\square", tag:"mo", output:"\u25AB", ttype:0},
{input:"\\Box", tag:"mo", output:"\u25A1", ttype:0},
{input:"\\wr", tag:"mo", output:"\u2240", ttype:0},
//standard functions
//Note DEFINITION *must* have tag:"mo" to work properly
{input:"\\arccos", tag:"mi", output:"arccos", ttype:1, func:true},
{input:"\\arcsin", tag:"mi", output:"arcsin", ttype:1, func:true},
{input:"\\arctan", tag:"mi", output:"arctan", ttype:1, func:true},
{input:"\\arg", tag:"mi", output:"arg", ttype:1, func:true},
{input:"\\cos", tag:"mi", output:"cos", ttype:1, func:true},
{input:"\\cosh", tag:"mi", output:"cosh", ttype:1, func:true},
{input:"\\cot", tag:"mi", output:"cot", ttype:1, func:true},
{input:"\\coth", tag:"mi", output:"coth", ttype:1, func:true},
{input:"\\csc", tag:"mi", output:"csc", ttype:1, func:true},
{input:"\\deg", tag:"mi", output:"deg", ttype:1, func:true},
{input:"\\det", tag:"mi", output:"det", ttype:1, func:true},
{input:"\\dim", tag:"mi", output:"dim", ttype:1, func:true}, //0?
{input:"\\exp", tag:"mi", output:"exp", ttype:1, func:true},
{input:"\\gcd", tag:"mi", output:"gcd", ttype:1, func:true}, //0?
{input:"\\hom", tag:"mi", output:"hom", ttype:1, func:true},
{input:"\\inf", tag:"mo", output:"inf", ttype:7},
{input:"\\ker", tag:"mi", output:"ker", ttype:1, func:true},
{input:"\\lg", tag:"mi", output:"lg", ttype:1, func:true},
{input:"\\lim", tag:"mo", output:"lim", ttype:7},
{input:"\\liminf", tag:"mo", output:"liminf", ttype:7},
{input:"\\limsup", tag:"mo", output:"limsup", ttype:7},
{input:"\\ln", tag:"mi", output:"ln", ttype:1, func:true},
{input:"\\log", tag:"mi", output:"log", ttype:1, func:true},
{input:"\\max", tag:"mo", output:"max", ttype:7},
{input:"\\min", tag:"mo", output:"min", ttype:7},
{input:"\\Pr", tag:"mi", output:"Pr", ttype:1, func:true},
{input:"\\sec", tag:"mi", output:"sec", ttype:1, func:true},
{input:"\\sin", tag:"mi", output:"sin", ttype:1, func:true},
{input:"\\sinh", tag:"mi", output:"sinh", ttype:1, func:true},
{input:"\\sup", tag:"mo", output:"sup", ttype:7},
{input:"\\tan", tag:"mi", output:"tan", ttype:1, func:true},
{input:"\\tanh", tag:"mi", output:"tanh", ttype:1, func:true},
//arrows
{input:"\\gets", tag:"mo", output:"\u2190", ttype:0},
{input:"\\leftarrow", tag:"mo", output:"\u2190", ttype:0},
{input:"\\to", tag:"mo", output:"\u2192", ttype:0},
{input:"\\rightarrow", tag:"mo", output:"\u2192", ttype:0},
{input:"\\leftrightarrow", tag:"mo", output:"\u2194", ttype:0},
{input:"\\uparrow", tag:"mo", output:"\u2191", ttype:0},
{input:"\\downarrow", tag:"mo", output:"\u2193", ttype:0},
{input:"\\updownarrow", tag:"mo", output:"\u2195", ttype:0},
{input:"\\Leftarrow", tag:"mo", output:"\u21D0", ttype:0},
{input:"\\Rightarrow", tag:"mo", output:"\u21D2", ttype:0},
{input:"\\Leftrightarrow", tag:"mo", output:"\u21D4", ttype:0},
{input:"\\iff", tag:"mo", output:"~\\Longleftrightarrow~", ttype:8},
{input:"\\Uparrow", tag:"mo", output:"\u21D1", ttype:0},
{input:"\\Downarrow", tag:"mo", output:"\u21D3", ttype:0},
{input:"\\Updownarrow", tag:"mo", output:"\u21D5", ttype:0},
{input:"\\mapsto", tag:"mo", output:"\u21A6", ttype:0},
{input:"\\longleftarrow", tag:"mo", output:"\u2190", ttype:11},
{input:"\\longrightarrow", tag:"mo", output:"\u2192", ttype:11},
{input:"\\longleftrightarrow", tag:"mo", output:"\u2194", ttype:11},
{input:"\\Longleftarrow", tag:"mo", output:"\u21D0", ttype:11},
{input:"\\Longrightarrow", tag:"mo", output:"\u21D2", ttype:11},
{input:"\\Longleftrightarrow", tag:"mo", output:"\u21D4", ttype:11},
{input:"\\longmapsto", tag:"mo", output:"\u21A6", ttype:0}, // disaster if LONG
//commands with argument
{input:"\\sqrt", tag:"msqrt", output:"sqrt", ttype:1},
{input:"\\root", tag:"mroot", output:"root", ttype:2},
{input:"\\frac", tag:"mfrac", output:"/", ttype:2},
{input:"\\stackrel", tag:"mover", output:"stackrel", ttype:2},
{input:"\\atop", tag:"mfrac", output:"", ttype:3},
{input:"\\choose", tag:"mfrac", output:"", ttype:3},
{input:"_", tag:"msub", output:"_", ttype:3},
{input:"^", tag:"msup", output:"^", ttype:3},
{input:"\\mathrm", tag:"mtext", output:"text", ttype:9},
{input:"\\mbox", tag:"mtext", output:"mbox", ttype:9},
//diacritical marks
{input:"\\acute", tag:"mover", output:"\u00B4", ttype:1, acc:true},
{input:"\\grave", tag:"mover", output:"\u0060", ttype:1, acc:true},
{input:"\\breve", tag:"mover", output:"\u02D8", ttype:1, acc:true},
{input:"\\check", tag:"mover", output:"\u02C7", ttype:1, acc:true},
{input:"\\dot", tag:"mover", output:".", ttype:1, acc:true},
{input:"\\ddot", tag:"mover", output:"..", ttype:1, acc:true},
{input:"\\mathring", tag:"mover", output:"\u00B0", ttype:1, acc:true},
{input:"\\vec", tag:"mover", output:"\u20D7", ttype:1, acc:true},
{input:"\\overrightarrow",tag:"mover",output:"\u20D7", ttype:1, acc:true},
{input:"\\overleftarrow",tag:"mover", output:"\u20D6", ttype:1, acc:true},
{input:"\\hat", tag:"mover", output:"\u005E", ttype:1, acc:true},
{input:"\\widehat", tag:"mover", output:"\u0302", ttype:1, acc:true},
{input:"\\tilde", tag:"mover", output:"~", ttype:1, acc:true},
{input:"\\widetilde", tag:"mover", output:"\u02DC", ttype:1, acc:true},
{input:"\\bar", tag:"mover", output:"\u203E", ttype:1, acc:true},
{input:"\\overbrace", tag:"mover", output:"\u23B4", ttype:1, acc:true},
{input:"\\overline", tag:"mover", output:"\u00AF", ttype:1, acc:true},
{input:"\\underbrace", tag:"munder", output:"\u23B5", ttype:1, acc:true},
{input:"\\underline", tag:"munder", output:"\u00AF", ttype:1, acc:true},
//typestyles and fonts
{input:"\\displaystyle",tag:"mstyle",atname:"displaystyle",atval:"true", ttype:1},
{input:"\\textstyle",tag:"mstyle",atname:"displaystyle",atval:"false", ttype:1},
{input:"\\scriptstyle",tag:"mstyle",atname:"scriptlevel",atval:"1", ttype:1},
{input:"\\scriptscriptstyle",tag:"mstyle",atname:"scriptlevel",atval:"2", ttype:1},
{input:"\\textrm", tag:"mstyle", output:"\\mathrm", ttype: 8},
{input:"\\mathbf", tag:"mstyle", atname:"mathvariant", atval:"bold", ttype:1},
{input:"\\textbf", tag:"mstyle", atname:"mathvariant", atval:"bold", ttype:1},
{input:"\\mathit", tag:"mstyle", atname:"mathvariant", atval:"italic", ttype:1},
{input:"\\textit", tag:"mstyle", atname:"mathvariant", atval:"italic", ttype:1},
{input:"\\mathtt", tag:"mstyle", atname:"mathvariant", atval:"monospace", ttype:1},
{input:"\\texttt", tag:"mstyle", atname:"mathvariant", atval:"monospace", ttype:1},
{input:"\\mathsf", tag:"mstyle", atname:"mathvariant", atval:"sans-serif", ttype:1},
{input:"\\mathbb", tag:"mstyle", atname:"mathvariant", atval:"double-struck", ttype:1, codes:this.AMbbb},
{input:"\\mathcal",tag:"mstyle", atname:"mathvariant", atval:"script", ttype:1, codes:this.AMcal},
{input:"\\mathfrak",tag:"mstyle",atname:"mathvariant", atval:"fraktur",ttype:1, codes:this.AMfrk}
],
AMcompareNames: function(s1,s2) {
if (s1.input > s2.input) return 1
else return -1;
},
init: function() {
this.AMsymbols.sort(this.AMcompareNames);
for (var i=0; i<this.AMsymbols.length; i++) this.AMnames[i] = this.AMsymbols[i].input;
},
AMcreateElementMathML: function(t) {
if (this.isIE) return document.createElement("m:"+t);
else return document.createElementNS(this.AMmathml,t);
},
AMcreateMmlNode: function(t,frag) {
if (this.isIE) var node = document.createElement("m:"+t);
else var node = document.createElementNS(this.AMmathml,t);
node.appendChild(frag);
return node;
},
newCommand: function(oldstr,newstr) {
this.AMsymbols = this.AMsymbols.concat([{input:oldstr, tag:"mo", output:newstr, ttype:this.DEFINITION}]);
},
AMremoveCharsAndBlanks: function(str,n) {
//remove n characters and any following blanks
var st;
st = str.slice(n);
for (var i=0; i<st.length && st.charCodeAt(i)<=32; i=i+1);
return st.slice(i);
},
AMposition: function(arr, str, n) {
// return position >=n where str appears or would be inserted
// assumes arr is sorted
if (n==0) {
var h,m;
n = -1;
h = arr.length;
while (n+1<h) {
m = (n+h) >> 1;
if (arr[m]<str) n = m; else h = m;
}
return h;
} else
for (var i=n; i<arr.length && arr[i]<str; i++);
return i; // i=arr.length || arr[i]>=str
},
AMgetSymbol: function(str) {
//return maximal initial substring of str that appears in AMnames
//return null if there is none
var k = 0; //new pos
var j = 0; //old pos
var mk; //match pos
var st;
var tagst;
var match = "";
var more = true;
for (var i=1; i<=str.length && more; i++) {
st = str.slice(0,i); //initial substring of length i
j = k;
k = this.AMposition(this.AMnames, st, j);
if (k<this.AMnames.length && str.slice(0,this.AMnames[k].length)==this.AMnames[k]){
match = this.AMnames[k];
mk = k;
i = match.length;
}
more = k<this.AMnames.length && str.slice(0,this.AMnames[k].length)>=this.AMnames[k];
}
this.AMpreviousSymbol=this.AMcurrentSymbol;
if (match!=""){
this.AMcurrentSymbol=this.AMsymbols[mk].ttype;
return this.AMsymbols[mk];
}
this.AMcurrentSymbol=this.CONST;
k = 1;
st = str.slice(0,1); //take 1 character
if ("0"<=st && st<="9") tagst = "mn";
else tagst = (("A">st || st>"Z") && ("a">st || st>"z")?"mo":"mi");
return {input:st, tag:tagst, output:st, ttype:this.CONST};
},
AMpreviousSymbol: null,
AMcurrentSymbol: null,
AMparseSexpr: function(str) { //parses str and returns [node,tailstr,(node)tag]
var symbol, node, result, result2, i, st,// rightvert = false,
newFrag = document.createDocumentFragment();
str = this.AMremoveCharsAndBlanks(str,0);
symbol = this.AMgetSymbol(str); //either a token or a bracket or empty
if (symbol == null || symbol.ttype == this.RIGHTBRACKET)
return [null,str,null];
if (symbol.ttype == this.DEFINITION) {
str = symbol.output+this.AMremoveCharsAndBlanks(str,symbol.input.length);
symbol = this.AMgetSymbol(str);
if (symbol == null || symbol.ttype == this.RIGHTBRACKET)
return [null,str,null];
}
str = this.AMremoveCharsAndBlanks(str,symbol.input.length);
switch (symbol.ttype) {
case this.SPACE:
node = this.AMcreateElementMathML(symbol.tag);
node.setAttribute(symbol.atname,symbol.atval);
return [node,str,symbol.tag];
case this.UNDEROVER:
if (this.isIE) {
if (symbol.input.substr(0,4) == "\\big") { // botch for missing symbols
str = "\\"+symbol.input.substr(4)+str; // make \bigcup = \cup etc.
symbol = this.AMgetSymbol(str);
symbol.ttype = this.UNDEROVER;
str = this.AMremoveCharsAndBlanks(str,symbol.input.length);
}
}
return [this.AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output)),str,symbol.tag];
case this.CONST:
var output = symbol.output;
if (this.isIE) {
if (symbol.input == "'")
output = "\u2032";
else if (symbol.input == "''")
output = "\u2033";
else if (symbol.input == "'''")
output = "\u2033\u2032";
else if (symbol.input == "''''")
output = "\u2033\u2033";
else if (symbol.input == "\\square")
output = "\u25A1"; // same as \Box
else if (symbol.input.substr(0,5) == "\\frac") {
// botch for missing fractions
var denom = symbol.input.substr(6,1);
if (denom == "5" || denom == "6") {
str = symbol.input.replace(/\\frac/,"\\frac ")+str;
return [node,str,symbol.tag];
}
}
}
node = this.AMcreateMmlNode(symbol.tag,document.createTextNode(output));
return[node,str,symbol.tag];
case this.LONG: // added by DRW
node = this.AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output));
node.setAttribute("minsize","1.5");
node.setAttribute("maxsize","1.5");
node = this.AMcreateMmlNode("mover",node);
node.appendChild(this.AMcreateElementMathML("mspace"));
return [node,str,symbol.tag];
case this.STRETCHY: // added by DRW
if (this.isIE && symbol.input == "\\backslash")
symbol.output = "\\"; // doesn't expand, but then nor does "\u2216"
node = this.AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output));
if (symbol.input == "|" || symbol.input == "\\vert" || symbol.input == "\\|" || symbol.input == "\\Vert") {
node.setAttribute("lspace","0em");
node.setAttribute("rspace","0em");
}
node.setAttribute("maxsize",symbol.atval); // don't allow to stretch here
if (symbol.rtag != null)
return [node,str,symbol.rtag];
else
return [node,str,symbol.tag];
case this.BIG: // added by DRW
var atval = symbol.atval;
if (this.isIE)
atval = symbol.ieval;
symbol = this.AMgetSymbol(str);
if (symbol == null)
return [null,str,null];
str = this.AMremoveCharsAndBlanks(str,symbol.input.length);
node = this.AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output));
if (this.isIE) { // to get brackets to expand
var space = this.AMcreateElementMathML("mspace");
space.setAttribute("height",atval+"ex");
node = this.AMcreateMmlNode("mrow",node);
node.appendChild(space);
} else { // ignored in IE
node.setAttribute("minsize",atval);
node.setAttribute("maxsize",atval);
}
return [node,str,symbol.tag];
case this.LEFTBRACKET: //read (expr+)
if (symbol.input == "\\left") { // left what?
symbol = this.AMgetSymbol(str);
if (symbol != null) {
if (symbol.input == ".")
symbol.invisible = true;
str = this.AMremoveCharsAndBlanks(str,symbol.input.length);
}
}
result = this.AMparseExpr(str,true,false);
if (symbol==null || (typeof symbol.invisible == "boolean" && symbol.invisible))
node = this.AMcreateMmlNode("mrow",result[0]);
else {
node = this.AMcreateMmlNode("mo",document.createTextNode(symbol.output));
node = this.AMcreateMmlNode("mrow",node);
node.appendChild(result[0]);
}
return [node,result[1],result[2]];
case this.MATRIX: //read (expr+)
if (symbol.input == "\\begin{array}") {
var mask = "";
symbol = this.AMgetSymbol(str);
str = this.AMremoveCharsAndBlanks(str,0);
if (symbol == null)
mask = "l";
else {
str = this.AMremoveCharsAndBlanks(str,symbol.input.length);
if (symbol.input != "{")
mask = "l";
else do {
symbol = this.AMgetSymbol(str);
if (symbol != null) {
str = this.AMremoveCharsAndBlanks(str,symbol.input.length);
if (symbol.input != "}")
mask = mask+symbol.input;
}
} while (symbol != null && symbol.input != "" && symbol.input != "}");
}
result = this.AMparseExpr("{"+str,true,true);
node = this.AMcreateMmlNode("mtable",result[0]);
mask = mask.replace(/l/g,"left ");
mask = mask.replace(/r/g,"right ");
mask = mask.replace(/c/g,"center ");
node.setAttribute("columnalign",mask);
node.setAttribute("displaystyle","false");
if (this.isIE)
return [node,result[1],null];
// trying to get a *little* bit of space around the array
// (IE already includes it)
var lspace = this.AMcreateElementMathML("mspace");
lspace.setAttribute("width","0.167em");
var rspace = this.AMcreateElementMathML("mspace");
rspace.setAttribute("width","0.167em");
var node1 = this.AMcreateMmlNode("mrow",lspace);
node1.appendChild(node);
node1.appendChild(rspace);
return [node1,result[1],null];
} else { // eqnarray
result = this.AMparseExpr("{"+str,true,true);
node = this.AMcreateMmlNode("mtable",result[0]);
if (this.isIE)
node.setAttribute("columnspacing","0.25em"); // best in practice?
else
node.setAttribute("columnspacing","0.167em"); // correct (but ignored?)
node.setAttribute("columnalign","right center left");
node.setAttribute("displaystyle","true");
node = this.AMcreateMmlNode("mrow",node);
return [node,result[1],null];
}
case this.TEXT:
if (str.charAt(0)=="{") i=str.indexOf("}");
else i = 0;
if (i==-1) i = str.length;
st = str.slice(1,i);
if (st.charAt(0) == " ") {
node = this.AMcreateElementMathML("mspace");
node.setAttribute("width","0.33em"); // was 1ex
newFrag.appendChild(node);
}
newFrag.appendChild(this.AMcreateMmlNode(symbol.tag,document.createTextNode(st)));
if (st.charAt(st.length-1) == " ") {
node = this.AMcreateElementMathML("mspace");
node.setAttribute("width","0.33em"); // was 1ex
newFrag.appendChild(node);
}
str = this.AMremoveCharsAndBlanks(str,i+1);
return [this.AMcreateMmlNode("mrow",newFrag),str,null];
case this.UNARY:
result = this.AMparseSexpr(str);
if (result[0]==null) return [this.AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output)),str];
if (typeof symbol.func == "boolean" && symbol.func) { // functions hack
st = str.charAt(0);
if (st=="^" || st=="_" || st==",") {
return [this.AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output)),str,symbol.tag];
} else {
node = this.AMcreateMmlNode("mrow",this.AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output)));
if (this.isIE) {
var space = this.AMcreateElementMathML("mspace");
space.setAttribute("width","0.167em");
node.appendChild(space);
}
node.appendChild(result[0]);
return [node,result[1],symbol.tag];
}
}
if (symbol.input == "\\sqrt") { // sqrt
if (this.isIE) { // set minsize, for \surd
var space = this.AMcreateElementMathML("mspace");
space.setAttribute("height","1.2ex");
space.setAttribute("width","0em"); // probably no effect
node = this.AMcreateMmlNode(symbol.tag,result[0])
node.appendChild(space);
return [node,result[1],symbol.tag];
} else
return [this.AMcreateMmlNode(symbol.tag,result[0]),result[1],symbol.tag];
} else if (typeof symbol.acc == "boolean" && symbol.acc) { // accent
node = this.AMcreateMmlNode(symbol.tag,result[0]);
var output = symbol.output;
if (this.isIE) {
if (symbol.input == "\\hat")
output = "\u0302";
else if (symbol.input == "\\widehat")
output = "\u005E";
else if (symbol.input == "\\bar")
output = "\u00AF";
else if (symbol.input == "\\grave")
output = "\u0300";
else if (symbol.input == "\\tilde")
output = "\u0303";
}
var node1 = this.AMcreateMmlNode("mo",document.createTextNode(output));
if (symbol.input == "\\vec" || symbol.input == "\\check") // don't allow to stretch
node1.setAttribute("maxsize","1.2"); // why doesn't "1" work? \vec nearly disappears in firefox
if (this.isIE && symbol.input == "\\bar")
node1.setAttribute("maxsize","0.5");
if (symbol.input == "\\underbrace" || symbol.input == "\\underline")
node1.setAttribute("accentunder","true");
else
node1.setAttribute("accent","true");
node.appendChild(node1);
if (symbol.input == "\\overbrace" || symbol.input == "\\underbrace")
node.ttype = UNDEROVER;
return [node,result[1],symbol.tag];
} else { // font change or displaystyle command
if (!this.isIE && typeof symbol.codes != "undefined") {
for (i=0; i<result[0].childNodes.length; i++)
if (result[0].childNodes[i].nodeName=="mi" || result[0].nodeName=="mi") {
st = (result[0].nodeName=="mi"?result[0].firstChild.nodeValue:result[0].childNodes[i].firstChild.nodeValue);
var newst = [];
for (var j=0; j<st.length; j++)
if (st.charCodeAt(j)>64 && st.charCodeAt(j)<91) newst = newst + String.fromCharCode(symbol.codes[st.charCodeAt(j)-65]);
else newst = newst + st.charAt(j);
if (result[0].nodeName=="mi")
result[0]=this.AMcreateElementMathML("mo").appendChild(document.createTextNode(newst));
else result[0].replaceChild(this.AMcreateElementMathML("mo").appendChild(document.createTextNode(newst)),result[0].childNodes[i]);
}
}
node = this.AMcreateMmlNode(symbol.tag,result[0]);
node.setAttribute(symbol.atname,symbol.atval);
if (symbol.input == "\\scriptstyle" || symbol.input == "\\scriptscriptstyle")
node.setAttribute("displaystyle","false");
return [node,result[1],symbol.tag];
}
case this.BINARY:
result = this.AMparseSexpr(str);
if (result[0]==null) return [this.AMcreateMmlNode("mo",document.createTextNode(symbol.input)),str,null];
result2 = this.AMparseSexpr(result[1]);
if (result2[0]==null) return [this.AMcreateMmlNode("mo",document.createTextNode(symbol.input)),str,null];
if (symbol.input=="\\root" || symbol.input=="\\stackrel")
newFrag.appendChild(result2[0]);
newFrag.appendChild(result[0]);
if (symbol.input=="\\frac") newFrag.appendChild(result2[0]);
return [this.AMcreateMmlNode(symbol.tag,newFrag),result2[1],symbol.tag];
case this.INFIX:
str = this.AMremoveCharsAndBlanks(str,symbol.input.length);
return [this.AMcreateMmlNode("mo",document.createTextNode(symbol.output)),str,symbol.tag];
default:
return [this.AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output)),str,symbol.tag];
}
},
AMparseIexpr: function(str) {
var symbol, sym1, sym2, node, result, tag, underover;
str = this.AMremoveCharsAndBlanks(str,0);
sym1 = this.AMgetSymbol(str);
result = this.AMparseSexpr(str);
node = result[0];
str = result[1];
tag = result[2];
symbol = this.AMgetSymbol(str);
if (symbol.ttype == this.INFIX) {
str = this.AMremoveCharsAndBlanks(str,symbol.input.length);
result = this.AMparseSexpr(str);
if (result[0] == null) // show box in place of missing argument
result[0] = this.AMcreateMmlNode("mo",document.createTextNode("\u25A1"));
str = result[1];
tag = result[2];
if (symbol.input == "_" || symbol.input == "^") {
sym2 = this.AMgetSymbol(str);
tag = null; // no space between x^2 and a following sin, cos, etc.
// This is for \underbrace and \overbrace
underover = ((sym1.ttype == this.UNDEROVER) || (node.ttype == this.UNDEROVER));
if (symbol.input == "_" && sym2.input == "^") {
str = this.AMremoveCharsAndBlanks(str,sym2.input.length);
var res2 = this.AMparseSexpr(str);
str = res2[1];
tag = res2[2]; // leave space between x_1^2 and a following sin etc.
node = this.AMcreateMmlNode((underover?"munderover":"msubsup"),node);
node.appendChild(result[0]);
node.appendChild(res2[0]);
} else if (symbol.input == "_") {
node = this.AMcreateMmlNode((underover?"munder":"msub"),node);
node.appendChild(result[0]);
} else {
node = this.AMcreateMmlNode((underover?"mover":"msup"),node);
node.appendChild(result[0]);
}
node = this.AMcreateMmlNode("mrow",node); // so sum does not stretch
} else {
node = this.AMcreateMmlNode(symbol.tag,node);
if (symbol.input == "\\atop" || symbol.input == "\\choose")
node.setAttribute("linethickness","0ex");
node.appendChild(result[0]);
if (symbol.input == "\\choose")
node = this.AMcreateMmlNode("mfenced",node);
}
}
return [node,str,tag];
},
AMparseExpr: function(str,rightbracket,matrix) {
var symbol, node, result, i, tag,
newFrag = document.createDocumentFragment();
do {
str = this.AMremoveCharsAndBlanks(str,0);
result = this.AMparseIexpr(str);
node = result[0];
str = result[1];
tag = result[2];
symbol = this.AMgetSymbol(str);
if (node!=undefined) {
if ((tag == "mn" || tag == "mi") && symbol!=null && typeof symbol.func == "boolean" && symbol.func) {
// Add space before \sin in 2\sin x or x\sin x
var space = this.AMcreateElementMathML("mspace");
space.setAttribute("width","0.167em");
node = this.AMcreateMmlNode("mrow",node);
node.appendChild(space);
}
newFrag.appendChild(node);
}
} while ((symbol.ttype != this.RIGHTBRACKET) && symbol!=null && symbol.output!="");
tag = null;
if (symbol.ttype == this.RIGHTBRACKET) {
if (symbol.input == "\\right") { // right what?
str = this.AMremoveCharsAndBlanks(str,symbol.input.length);
symbol = this.AMgetSymbol(str);
if (symbol != null && symbol.input == ".")
symbol.invisible = true;
if (symbol != null)
tag = symbol.rtag;
}
if (symbol!=null)
str = this.AMremoveCharsAndBlanks(str,symbol.input.length); // ready to return
var len = newFrag.childNodes.length;
if (matrix && len>0 && newFrag.childNodes[len-1].nodeName == "mrow" && len>1 && newFrag.childNodes[len-2].nodeName == "mo" && newFrag.childNodes[len-2].firstChild.nodeValue == "&") { //matrix
var pos = []; // positions of ampersands
var m = newFrag.childNodes.length;
for (i=0; matrix && i<m; i=i+2) {
pos[i] = [];
node = newFrag.childNodes[i];
for (var j=0; j<node.childNodes.length; j++)
if (node.childNodes[j].firstChild.nodeValue=="&") pos[i][pos[i].length]=j;
}
var row, frag, n, k, table = document.createDocumentFragment();
for (i=0; i<m; i=i+2) {
row = document.createDocumentFragment();
frag = document.createDocumentFragment();
node = newFrag.firstChild; // <mrow> -&-&...&-&- </mrow>
n = node.childNodes.length;
k = 0;
for (j=0; j<n; j++) {
if (typeof pos[i][k] != "undefined" && j==pos[i][k]){
node.removeChild(node.firstChild); //remove &
row.appendChild(this.AMcreateMmlNode("mtd",frag));
k++;
} else frag.appendChild(node.firstChild);
}
row.appendChild(this.AMcreateMmlNode("mtd",frag));
if (newFrag.childNodes.length>2) {
newFrag.removeChild(newFrag.firstChild); //remove <mrow> </mrow>
newFrag.removeChild(newFrag.firstChild); //remove <mo>&</mo>
}
table.appendChild(this.AMcreateMmlNode("mtr",row));
}
return [table,str];
}
if (typeof symbol.invisible != "boolean" || !symbol.invisible) {
node = this.AMcreateMmlNode("mo",document.createTextNode(symbol.output));
newFrag.appendChild(node);
}
}
return [newFrag,str,tag];
},
AMparseMath: function(str) {
var result, node = this.AMcreateElementMathML("mstyle");
node.appendChild(this.AMparseExpr(str.replace(/^\s+/g,""),false,false)[0]);
node = this.AMcreateMmlNode("math",node);
return node;
},
AMstrarr2docFrag: function(arr) {
var newFrag=document.createDocumentFragment();
newFrag.appendChild(this.AMparseMath(arr));
return newFrag;
}
};
config.macros.LaTeXMathMLPlugin.init();
config.formatters.push({
name: "eqmath0",
match: "\\$\\$",
lookaheadRegExp: /\$\$((?:.|\n)*?)\$\$/mg,
handler: function(w){
this.lookaheadRegExp.lastIndex = w.matchStart;
var lookaheadMatch = this.lookaheadRegExp.exec(w.source);
if(lookaheadMatch){
var eq = createTiddlyElement(w.output,"div");
eq.style.textAlign='center';
eq.appendChild(config.macros.LaTeXMathMLPlugin.AMstrarr2docFrag("\\displaystyle\{"+lookaheadMatch[1]+"\}"));
w.nextMatch = lookaheadMatch.index + lookaheadMatch[0].length;
}
}
});
config.formatters.push({
name: "eqmath1",
match: "\\$",
lookaheadRegExp: /\$((?:.|\n)*?)\$/mg,
handler: function(w){
this.lookaheadRegExp.lastIndex = w.matchStart;
var lookaheadMatch = this.lookaheadRegExp.exec(w.source);
if(lookaheadMatch){
var eq = createTiddlyElement(w.output,"span");
eq.appendChild(config.macros.LaTeXMathMLPlugin.AMstrarr2docFrag(lookaheadMatch[1]));
w.nextMatch = lookaheadMatch.index + lookaheadMatch[0].length;
}
}
});
config.shadowTiddlers.LaTeXMathMLPluginDoc="The documentation is available [[here.|http://www.math.ist.utl.pt/~psoares/addons.html#LaTeXMathMLPluginDoc]]";
//}}}
//{{{
with(config.macros.LaTeXMathMLPlugin){
newCommand("\\nle","\u2270");
newCommand("\\R","\u211D");
init();
}
//}}}
!Description
This plugin is a modification of a set of ~JavaScript functions to convert ~LaTeX math notation to Presentation ~MathML written by Douglas Woodall. The original notice can be found at the end of this text. The most important changes were:
#the substitution mechanism of ~LaTeX snippets (enclosed by {{{$...$}}} or {{{$$...$$}}}) was replaced by a couple of ~TiddlyWiki formatters
#centered equations (enclosed by {{{$$...$$}}}) are properly handled
#~MathML output can be decorated by CSS rules such as
{{{
math {
font-family: sans-serif,arial;
color: red;
}
}}}
!Installation
To use this plugin with Internet Explorer (IE) it is needed the [[MathPlayer|http://www.dessci.com/en/products/mathplayer/]] plugin for IE and the following lines should be added to the MarkupPreHead tiddler:
{{{
<html xmlns:m="http://www.w3.org/1998/Math/MathML">
<object id="mathplayer" classid="clsid:32F66A20-7614-11D4-BD11-00104BD3F987"></object>
<?import namespace="m" implementation="#mathplayer"?>
}}}
!Adding new symbols
The standard symbol table can be extended by adding additional symbols. This is done by adding a few lines of ~JavaScript code as in [[here|LaTeXMathMLPluginComp]].
You first have to find the four-digit hexadecimal Unicode value for these symbols by looking them up at, say, [[here|http://www.w3.org/TR/MathML2/chapter6.html#chars.entity.tables]].
!Credits
A final word of appreciation for the work of Douglas Woodall and Peter Jipsen on promoting the presentation of beautiful math in the web.
!Revision history
*1.1 06/10/2007
**Complete refactoring of the code. No more global variables!
*1.0.1 15/09/2007
**Included missing function 'newcommand' that allows the extension of the set of symbols available
*1.0.0 12/09/2007
**Initial release
!Original notice
{{{
LaTeXMathML.js
==============
This file, in this form, is due to Douglas Woodall, June 2006.
It contains JavaScript functions to convert (most simple) LaTeX
math notation to Presentation MathML. It was obtained by
downloading the file ASCIIMathML.js from
http://www1.chapman.edu/~jipsen/mathml/asciimathdownload/
and modifying it so that it carries out ONLY those conversions
that would be carried out in LaTeX. A description of the original
file, with examples, can be found at
www1.chapman.edu/~jipsen/mathml/asciimath.html
ASCIIMathML: Math on the web for everyone
Here is the header notice from the original file:
ASCIIMathML.js
==============
This file contains JavaScript functions to convert ASCII math notation
to Presentation MathML. The conversion is done while the (X)HTML page
loads, and should work with Firefox/Mozilla/Netscape 7+ and Internet
Explorer 6+MathPlayer (http://www.dessci.com/en/products/mathplayer/).
Just add the next line to your (X)HTML page with this file in the same folder:
<script type="text/javascript" src="ASCIIMathML.js"></script>
This is a convenient and inexpensive solution for authoring MathML.
Version 1.4.7 Dec 15, 2005, (c) Peter Jipsen http://www.chapman.edu/~jipsen
Latest version at http://www.chapman.edu/~jipsen/mathml/ASCIIMathML.js
For changes see http://www.chapman.edu/~jipsen/mathml/asciimathchanges.txt
If you use it on a webpage, please send the URL to jipsen@chapman.edu
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License (at http://www.gnu.org/copyleft/gpl.html)
for more details.
}}}
/***
|''Name:''|LegacyStrikeThroughPlugin|
|''Description:''|Support for legacy (pre 2.1) strike through formatting|
|''Version:''|1.0.2|
|''Date:''|Jul 21, 2006|
|''Source:''|http://www.tiddlywiki.com/#LegacyStrikeThroughPlugin|
|''Author:''|MartinBudden (mjbudden (at) gmail (dot) com)|
|''License:''|[[BSD open source license]]|
|''CoreVersion:''|2.1.0|
***/
//{{{
// Ensure that the LegacyStrikeThrough Plugin is only installed once.
if(!version.extensions.LegacyStrikeThroughPlugin) {
version.extensions.LegacyStrikeThroughPlugin = {installed:true};
config.formatters.push(
{
name: "legacyStrikeByChar",
match: "==",
termRegExp: /(==)/mg,
element: "strike",
handler: config.formatterHelpers.createElementAndWikify
});
} //# end of "install only once"
//}}}
[[Il Paradosso di Zeno – ca. 450 a.C.]]
[[Achille e la tartaruga]]
[[Achille riesce a raggiungere la tartaruga?]]
[[Quanto deve correre Achille?]]
[[Quando riuscirà Achille a raggiungere la tartaruga?]]
[[Dove raggiungerà Achille la tartaruga?]]
[[Serie Geometrica]]
<<toggleSideBar "" "" hide>>
<!--{{{-->
<link rel='alternate' type='application/rss+xml' title='RSS' href='index.xml'/>
<html xmlns:m="http://www.w3.org/1998/Math/MathML">
<object id="mathplayer" classid="clsid:32F66A20-7614-11D4-BD11-00104BD3F987"></object>
<?import namespace="m" implementation="#mathplayer"?>
<script type="text/javascript" src="TWASCIIsvg.js"></script>
<!--}}}-->
A famous result due to [[Euler|http://www-groups.dcs.st-and.ac.uk/~history/Mathematicians/Euler.html]] in ~LaTeX: $\sum_{n=1}^{+\infty}{\frac1{n^2}=\frac{\pi^2}6$
and again using {{{displaystyle}}}: $\displaystyle{\sum_{n=1}^{+\infty} \frac{1}{n^2}=\frac{\pi^2}{6}}$
and finally as a centered equation $$\sum_{n=1}^{+\infty} \frac{1}{n^2}=\frac{\pi^2}{6}.$$
Here is a graph of $x-\frac{x^3}{6}$ and $\sin(x)$ (double click on this tiddler to see the <embed> tag that produced it).
<html>
<center>
<embed id="graph"; src="d.svg";
script='width=300; height=150;
xmin=-2pi; xmax=2pi; xscl=1; axes(); stroke="red"
plot(sin(x))
stroke="blue"; strokedasharray="10,10"
plot(x-x^3/6,-4,4)'>
</center>
</html>
and a diagram illustrating why Pythagoras' Theorem holds:
<html>
<center>
<embed id="pythagoras"; src="d.svg";
script='width=400; height=170;
xmin=-4; xmax=4; xscl=1; ymin=1; noAxes(); noButton();
fill="yellow"
rect([1,1],[4,4])
rect([-4,1],[-1,4])
fill="red"
rect([-2,1],[-1,2])
fill="blue"
rect([-4,2],[-2,4])
fill="green"
path([[1,2],[2,4],[4,3],[3,1],[1,2]])
fill="none"
path([[-4,1],[-2,2],[-1,4]])'>
</center>
</html>
Go to http://www.w3c.org/Math.
<<closeAll>><<permaview>><<newTiddler>><<newJournal 'DD MMM YYYY'>><<saveChanges>><<slider chkSliderOptionsPanel OptionsPanel 'options »' 'Change TiddlyWiki advanced options'>>
|Nome|Fórmula molecular|Fórmula de estrutura condensada|h
|Met''ano''|$CH_4$|$CH_4$|
|Et''ano''|$C_2H_6$|$CH_3-CH_3$|
|Prop''ano''|$C_3H_8$|$CH_3-CH_2-CH_3$|
|But''ano''|$C_4H_{10}$|$CH_3-CH_2-CH_2 CH_3$|
|Pent''ano''|$C_5H_{12}$|$CH_3-CH_2-CH_2-CH_2-CH_3$|
|...|...|$\ldots$|
$$f(x) = \left\{\begin{array}{l l}
x^2 \sin \frac1x, & \textrm{if } x \ne 0, \\
0, & \textrm{if } x = 0 .
\end{array}\right.$$
$$\begin{eqnarray} x & = & \frac{-7 \pm \sqrt{49 - 24}}{6} \\
& = & -2 \textrm{ or } -\frac13. \end{eqnarray}$$
Last Updated:
Copyright © Mika Seppälä
<!--{{{-->
<div id='header' class='header'>
<div class='headerShadow'>
<span class='searchBar' macro='search'></span>
<span class='siteTitle' refresh='content' tiddler='SiteTitle'></span>
<span class='siteSubtitle' refresh='content' tiddler='SiteSubtitle'></span>
</div>
</div>
<div id='mainMenu'>
<span refresh='content' tiddler='MainMenu'></span>
<span id='noticeBoard' refresh='content' tiddler='NoticeBoard'></span>
</div>
<div id='sidebar'>
<div id='sidebarOptions' refresh='content' tiddler='MochaSideBarOptions'></div>
<div id='sidebarTabs' refresh='content' force='true' tiddler='SideBarTabs'></div>
</div>
<div id='displayArea'>
<div id='messageArea'></div>
<div id='tiddlerDisplay'></div>
</div>
<div id='contentFooter' refresh='content' tiddler='contentFooter'></div>
<!--}}}-->
É chiaro che Achille avrà raggiunto la tartaruga quando avrà corso $a$ metri oltre la tartaruga, annullando il vantaggio di partenza.
Date le velocità $v$ m/s per Achille, e $qv$ m/s, dove $0<q<1$, per la tartaruga, sappiamo che in un istante $t$, Achille avrà percorso $vt$ metri e la tartaruga $qvt$. Percui si ottiene che Achille impiega un tempo $t$ per raggiungere la tartaruga tale che:
$$vt=a+qvt$$
Questa equazione é di facile risoluzione. Achille riuscirà a raggiungere la tartaruga in $t=\frac{a}{v(1-q)}$ secondi. L'ipotesi iniziale $0<q<1$ implica che $1-q$ sia un numero positivo per il quale sia possibile dividere.
Cerchiamo adesso di capire [[dove Achille catturerà la tartaruga|Dove raggiungerà Achille la tartaruga?]] .
All'inizio, la distanza tra Achille e la tartaruga é pari ad $a$ metri. Quindi Achille deve correre $a$ metri durante i quali la tartaruga si porta avanti di $qa$ metri, dato che $q$ é il rapporto tra le loro velocità. Nel secondo momento, la distanza tra i due é $qa$ e quindi Achille deve correre per $qa$ metri. La tartaruga nel frattempo ne percorre $q^2a$.
Riassumendo, si ha:
|!Round |! Distanza tra i due |! Achille corre |! La tartaruga corre|
| 1 | $a$ metri | $a$ metri | $qa$ metri|
| 2 | $qa$ metri | $qa$ metri | $q²a$ metri|
| 3 | $q²a$ metri | $q²a$ metri | $q³a$ metri|
Possiamo quindi concludere che Achille deve correre $a+aq+aq²+aq³+…$ metri per raggiungere la tartaruga. Zeno basa il suo paradosso sul fatto che questa somma di termini sia infinita e che quindi; non potendo Achille coprire una distanza infinita, non possa raggiungere la tartaruga. Che dire?
Noi però sappiamo che i fatti dimostrano che Achille riesce a raggiungere la tartaruga e sappiamo anche [[quando la raggiunge|Quando riuscirà Achille a raggiungere la tartaruga?]].
''Question 1''
What is the correct answer?
<<quiz type:S= id:Q1>> A. The usual wrong answer.
<<quiz type:S id:Q1>> B. Another typical wrong answer.
<<quiz type:S value:true tiddler:Q1A id:Q1>> C. The correct answer
<<quiz type:S id:Q1>> D. A really weird answer.
''Question 2''
Classify the following sentences as ''true'' or ''false'':
| T/F ||h
|<<quiz type:T id:Q2.1>>|A. The usual wrong answer.|
|<<quiz type:T value:true id:Q2.2>>|B. Another typical wrong answer.|
|<<quiz type:T tiddler:Q1A id:Q2.3>>|C. The correct answer|
|<<quiz type:T value:true tiddler:Q1A id:Q2.4>>|D. A really weird answer.|
''Question 1'' (4 points)
Which field made Euclid's fame?
<<quiz type:S= id:Q1>> Algebra
<<quiz type:S id:Q1>> Probability
<<quiz type:S value:true tiddler:Q1A id:Q1 score:4>> Geometry
<<quiz type:S id:Q1>> Number theory
''Question 2'' (4 x 2 points)
| True/False |Classify the following sentences as ''true'' or ''false'':|h
| <<quiz type:T value:true score:2 id:Q2>> |Euclid was a greek mathematician|
| <<quiz type:T tiddler:Q1A score:2 id:Q5>> |Euclid is also known by his philosophical work|
| <<quiz type:T value:true score:2 id:Q3>> |Euclid's //Elements// is the oldest axiomatic deductive treatment of mathematics|
| <<quiz type:T tiddler:Q1A score:2 id:Q4>> |Euclid wrote his //Elements// in Athens|
''Question 3'' (4 points)
In which fields has Euclid worked?
<<quiz value:true tiddler:Q1A score:2>> Geometry
<<quiz score:-2>> Algebra
<<quiz score:-2>> Probability
<<quiz value:true score:2>> Number theory
''Question 4''
From the 19^^th^^ century on, several non-euclidean geometries were proposed. Does this means that Euclid was wrong?
+++[Answer|]
No, not at all. What was outstanding in Euclid's work on geometry was its ''axiomatic'' nature. That is, Euclid stated a minimum set of rules (the axioms) and systematically analysed its consequences. Other mathematicians changed the axioms and followed the same route opened by Euclid, exploring all possible consequences of those new axioms on new, and sometimes strange, spaces. On a flat space (space without curvature) the Euclidean geometry is still our best friend on lots of practical applications.
===
<<score>>
/***
|''Name:''|QuizzerPlugin|
|''Description:''|Makes quizzes with optional grades|
|''Version:''|1.0.1|
|''Date:''|Oct 07, 2007|
|''Source:''|http://www.math.ist.utl.pt/~psoares/addons.html|
|''Documentation:''|[[QuizzerPlugin Documentation|QuizzerPluginDoc]]|
|''Author:''|Paulo Soares|
|''License:''|[[Creative Commons Attribution-Share Alike 3.0 License|http://creativecommons.org/licenses/by-sa/3.0/]]|
|''~CoreVersion:''|2.1.0|
***/
//{{{
config.macros.quiz = {
wrongAnswer: "Incorrect answer. Please think again.",
rightAnswer: "That's right!",
trueValue: "True",
falseValue: "False",
handler: function(place,macroName,params,wikifier,paramString){
var par = paramString.parseParams("list",null,true);
var type = getParam(par,"type","M");
var panelType = (type.length>1) ? type.charAt(1) : "";
type = type.charAt(0);
var id = getParam(par,"id","");
if(id=="" && type!="M") return; // not sure about this
var value = getParam(par,"value",false);
var tiddler = getParam(par,"tiddler","");
var score = parseFloat(getParam(par,"score",0));
var toolTip = "";
if(type=="T"){
toolTip = this.trueValue;
if(value==false){
var tempTiddler=tiddler;
tiddler="";
var tempScore=score;
score=0;
}
}
this.createAnswer(place, type, toolTip, true, panelType, tiddler, value, score, id);
if(type=="T"){
tiddler=(value==false)?tempTiddler:"";
score=(value==false)?tempScore:0;
toolTip = this.falseValue;
this.createAnswer(place, type, toolTip, false, panelType, tiddler, !value, score, id);
}
},
createAnswer: function(place, type, toolTip, correction, panelType, tiddler, value, score, id){
var checked=false;
if(correction){
var correct = createTiddlyElement(place,"span","","correction","");
correct.style.display='none';
correct.style.fontWeight='bold';
checked=true;
}
if(type=="M"){
var btn = createTiddlyCheckbox(place,"",false,this.onClickAnswer);
} else {
var btn = createTiddlyRadiobox(place,"",checked,this.onClickAnswer,id);
}
btn.className = "answerItem";
btn.value=score;
if(toolTip!="") btn.title=toolTip;
var panelClass = (panelType=="=") ? "sliderPanel" : "floatingPanel"; //default to floating
var text = (tiddler!="") ? store.getTiddlerText(tiddler) : "";
if(text==""){text = (value) ? this.rightAnswer : this.wrongAnswer;}
var panel = createTiddlyElement(null,"div","",panelClass);
panel.style.display = "none"; //default to closed
panel.onclick=function(){this.style.display="none";};
place.appendChild(panel);
wikify(text,panel,null);
},
onClickAnswer: function(e){
if(!e) var e = window.event;
var panel = this.nextSibling;
if(this.checked){
var validated = 1;
var visiblePanel=document.getElementById('visiblePanel');
var scoreCard=document.getElementById('scoreCard');
if(visiblePanel){
visiblePanel.style.display="none";
visiblePanel.id="";
}
if(scoreCard){validated = scoreCard.value;}
if(validated==1){
panel.style.display = "block";
panel.id="visiblePanel";
var left= e.clientX +10;
panel.style.left = left + "px";
}
} else {
panel.style.display = "none";
panel.id="";
}
}
};
config.macros.score= {
trueSymbol: "✔",
falseSymbol: "✘",
label: "Score »",
handler: function(place,macroName,params,wikifier,paramString){
var btn = createTiddlyButton(place,this.label,"",this.checkOut);
btn.id="scoreCard";
btn.value=0;
},
checkOut: function(e){
if(this.value==1) return;
var total=score=points=0;
var answers=getElementsByClass("answerItem",document.getElementById('viewer'));
var answersLen=answers.length;
for(var i=0; i<answersLen; i++) {
points=parseFloat(answers[i].value);
score+=answers[i].checked*points;
if(points>0)total+=points;
var correct=answers[i].previousSibling;
if(correct.className=="correction"){
if(answers[i].checked == (points>0)){
correct.firstChild.data=config.macros.score.trueSymbol;
correct.style.color = '#0f0';
} else {
correct.firstChild.data=config.macros.score.falseSymbol;
correct.style.color = '#f00';
}
correct.style.display='inline';
}
}
var text = " " + score+"/"+total;
createTiddlyElement(document.getElementById('scoreCard'),"span","","",text);
this.value=1;
}
};
function getElementsByClass(searchClass,node,tag) {
var classElements = new Array();
if ( node == null ) node = document;
if ( tag == null ) tag = '*';
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
for (var i = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {classElements.push(els[i]);}
}
return classElements;
}
function createTiddlyRadiobox(theParent,caption,checked,onChange,id){
var cb = document.createElement("input");
cb.type = "radio";
cb.name = id;
cb.onclick = onChange;
theParent.appendChild(cb);
cb.checked = checked;
cb.className = "chkOptionInput";
if(caption) wikify(caption,theParent);
return cb;
}
setStylesheet("/*{{{*/\n.floatingPanel {\n color: black;\n;position: absolute;\nz-index: 10;\npadding: 0.5em;\nbackground-color: #eee;\nborder: 1px solid #333;\ncursor: crosshair}\n\n.sliderPanel {padding: 0.5em;\nborder: 1px dotted #333;\nwidth: auto;\ncursor: crosshair}\n\n/*}}}*/","AnswerPanelStyles");
config.shadowTiddlers.QuizzerPluginDoc="The documentation is missing. It is available [[here|http://www.math.ist.utl.pt/~psoares/addons.html#QuizzerPluginDoc]].";
//}}}
!!!!Syntax
The QuizzerPlugin has five parameters; most are optional:
//{{{
<<quiz [type:type[=]] [id:id] [tiddler:tiddler] [value:value] [score:score]>>
//}}}
Parameters:
*type (string)
**"M" (multiple answer checkbox) (default)
**"S" (single-answer radio button group)
**"T" (true/false question)
***append "=" for sliding panel (e.g., T=, S=, M=)
*id (string)
**required for types S and T only
***for type S value must be unique across a group of questions
***for type T value must be unique for each question
*tiddler (string, //optional//)
**display text from tiddler in the panel
**default is config.macros.answer.wrongAnswer or config.macros.answer.rightAnswer according to the value of the next parameter
*value
**use {{{value:true}}} to indicate that the true answer is right
**should be omitted otherwise
*score (number)
**sets the score for an answer
** default is 0
//{{{
config.macros.quiz.wrongAnswer="Resposta incorrecta. Por favor pense mais um pouco.";
config.macros.quiz.rightAnswer="Está correcto!";
config.macros.quiz.trueValue="Verdadeiro";
config.macros.quiz.falseValue="Falso";
config.macros.score.label="Pontuação »";
//}}}
<<bibliography Bibliography showAll:true>>
Ricordiamo che, secondo Zeno, Achille deve correre $a+aq+aq²+aq³+…$ metri per raggiungere la tartaruga. Secondo Zeno questa somma é infinita ed Achille non può correre una tale distanza. Ma noi abbiamo calcolato che Achille riesce a catturare la tartaruga dopo aver percorso $\frac{a}{1-q}$ metri. Il che significa che la somma infinita di termini $a+aq+aq²+aq³+…$ in realtà ha valore finito pari a $\frac{a}{1-q}$. La somma infinita di termini si denota anche con $\sum_{k=0}^{\infty}aq^k$ ed é conosciuta col nome di serie geometrica.
Abbiamo così derivato la formula per la somma di una serie geometrica:
$$a+aq+aq²+aq³+…= \sum_{k=0}^{\infty}aq^k=\frac{a}{1-q}$$
Si può dimostrare che questa formula é valida per $|q|<1$, cioé anche per valori negativi di $q$.
Il paradosso di Zeno in realtà é un modo per trovare la formula della somma di una serie geometrica.
/***
|Name|SinglePageModePlugin|
|Source|http://www.TiddlyTools.com/#SinglePageModePlugin|
|Documentation|http://www.TiddlyTools.com/#SinglePageModePluginInfo|
|Version|2.9.1|
|Author|Eric Shulman - ELS Design Studios|
|License|http://www.TiddlyTools.com/#LegalStatements <br>and [[Creative Commons Attribution-ShareAlike 2.5 License|http://creativecommons.org/licenses/by-sa/2.5/]]|
|~CoreVersion|2.1|
|Type|plugin|
|Requires||
|Overrides|Story.prototype.displayTiddler(), Story.prototype.displayTiddlers()|
|Options|##Configuration|
|Description|Show tiddlers one at a time with automatic permalink, or always open tiddlers at top/bottom of page.|
This plugin allows you to configure TiddlyWiki to navigate more like a traditional multipage web site with only one tiddler displayed at a time.
!!!!!Documentation
>see [[SinglePageModePluginInfo]]
!!!!!Configuration
<<<
<<option chkSinglePageMode>> Display one tiddler at a time
><<option chkSinglePageKeepFoldedTiddlers>> Don't auto-close folded tiddlers
><<option chkSinglePagePermalink>> Automatically permalink current tiddler
<<option chkTopOfPageMode>> Always open tiddlers at the top of the page
<<option chkBottomOfPageMode>> Always open tiddlers at the bottom of the page
<<option chkSinglePageAutoScroll>> Automatically scroll tiddler into view (if needed)
Notes:
* The "display one tiddler at a time" option can also be //temporarily// set/reset by including a 'paramifier' in the document URL: {{{#SPM:true}}} or {{{#SPM:false}}}.
* If more than one display mode is selected, 'one at a time' display takes precedence over both 'top' and 'bottom' settings, and if 'one at a time' setting is not used, 'top of page' takes precedence over 'bottom of page'.
* When using Apple's Safari browser, automatically setting the permalink causes an error and is disabled.
<<<
!!!!!Revisions
<<<
2008.04.08 [2.9.1] don't automatically add options to AdvancedOptions shadow tiddler
2008.04.02 [2.9.0] in displayTiddler(), when single-page mode is in use and a tiddler is being edited, ask for permission to save-and-close that tiddler, instead of just leaving it open.
| Please see [[SinglePageModePluginInfo]] for previous revision details |
2005.08.15 [1.0.0] Initial Release. Support for BACK/FORWARD buttons adapted from code developed by Clint Checketts.
<<<
!!!!!Code
***/
//{{{
version.extensions.SinglePageMode= {major: 2, minor: 9, revision: 1, date: new Date(2008,4,8)};
//}}}
//{{{
config.paramifiers.SPM = { onstart: function(v) {
config.options.chkSinglePageMode=eval(v);
if (config.options.chkSinglePageMode && config.options.chkSinglePagePermalink && !config.browser.isSafari) {
config.lastURL = window.location.hash;
if (!config.SPMTimer) config.SPMTimer=window.setInterval(function() {checkLastURL();},1000);
}
} };
//}}}
//{{{
if (config.options.chkSinglePageMode==undefined)
config.options.chkSinglePageMode=false;
if (config.options.chkSinglePageKeepFoldedTiddlers==undefined)
config.options.chkSinglePageKeepFoldedTiddlers=true;
if (config.options.chkSinglePagePermalink==undefined)
config.options.chkSinglePagePermalink=true;
if (config.options.chkTopOfPageMode==undefined)
config.options.chkTopOfPageMode=false;
if (config.options.chkBottomOfPageMode==undefined)
config.options.chkBottomOfPageMode=false;
if (config.options.chkSinglePageAutoScroll==undefined)
config.options.chkSinglePageAutoScroll=true;
//}}}
//{{{
config.SPMTimer = 0;
config.lastURL = window.location.hash;
function checkLastURL()
{
if (!config.options.chkSinglePageMode)
{ window.clearInterval(config.SPMTimer); config.SPMTimer=0; return; }
if (config.lastURL == window.location.hash) return; // no change in hash
var tids=convertUTF8ToUnicode(decodeURIComponent(window.location.hash.substr(1))).readBracketedList();
if (tids.length==1) // permalink (single tiddler in URL)
story.displayTiddler(null,tids[0]);
else { // restore permaview or default view
config.lastURL = window.location.hash;
if (!tids.length) tids=store.getTiddlerText("DefaultTiddlers").readBracketedList();
story.closeAllTiddlers();
story.displayTiddlers(null,tids);
}
}
if (Story.prototype.SPM_coreDisplayTiddler==undefined)
Story.prototype.SPM_coreDisplayTiddler=Story.prototype.displayTiddler;
Story.prototype.displayTiddler = function(srcElement,tiddler,template,animate,slowly)
{
var title=(tiddler instanceof Tiddler)?tiddler.title:tiddler;
var tiddlerElem=document.getElementById(story.idPrefix+title); // ==null unless tiddler is already displayed
var opt=config.options;
if (opt.chkSinglePageMode) {
story.forEachTiddler(function(tid,elem) {
// skip current tiddler and, optionally, tiddlers that are folded.
if ( tid==title
|| (opt.chkSinglePageKeepFoldedTiddlers && elem.getAttribute("folded")=="true"))
return;
// if a tiddler is being edited, ask before closing
if (elem.getAttribute("dirty")=="true") {
// if tiddler to be displayed is already shown, then leave active tiddlers editors as is
// (occurs when switching between view and edit modes)
if (tiddlerElem) return;
// otherwise, ask for permission
var msg="'"+tid+"' is currently being edited.\n\n";
msg+="Press OK to save and close this tiddler\nor press Cancel to leave it opened";
if (!confirm(msg)) return; else story.saveTiddler(tid);
}
story.closeTiddler(tid);
});
}
else if (opt.chkTopOfPageMode)
arguments[0]=null;
else if (opt.chkBottomOfPageMode)
arguments[0]="bottom";
if (opt.chkSinglePageMode && opt.chkSinglePagePermalink && !config.browser.isSafari) {
window.location.hash = encodeURIComponent(convertUnicodeToUTF8(String.encodeTiddlyLink(title)));
config.lastURL = window.location.hash;
document.title = wikifyPlain("SiteTitle") + " - " + title;
if (!config.SPMTimer) config.SPMTimer=window.setInterval(function() {checkLastURL();},1000);
}
if (tiddlerElem && tiddlerElem.getAttribute("dirty")=="true") { // editing... move tiddler without re-rendering
var isTopTiddler=(tiddlerElem.previousSibling==null);
if (!isTopTiddler && (opt.chkSinglePageMode || opt.chkTopOfPageMode))
tiddlerElem.parentNode.insertBefore(tiddlerElem,tiddlerElem.parentNode.firstChild);
else if (opt.chkBottomOfPageMode)
tiddlerElem.parentNode.insertBefore(tiddlerElem,null);
else this.SPM_coreDisplayTiddler.apply(this,arguments); // let CORE render tiddler
} else
this.SPM_coreDisplayTiddler.apply(this,arguments); // let CORE render tiddler
var tiddlerElem=document.getElementById(story.idPrefix+title);
if (tiddlerElem&&opt.chkSinglePageAutoScroll) {
var yPos=ensureVisible(tiddlerElem); // scroll to top of tiddler
var isTopTiddler=(tiddlerElem.previousSibling==null);
if (opt.chkSinglePageMode||opt.chkTopOfPageMode||isTopTiddler)
yPos=0; // scroll to top of page instead of top of tiddler
if (opt.chkAnimate) // defer scroll until 200ms after animation completes
setTimeout("window.scrollTo(0,"+yPos+")",config.animDuration+200);
else
window.scrollTo(0,yPos); // scroll immediately
}
}
if (Story.prototype.SPM_coreDisplayTiddlers==undefined)
Story.prototype.SPM_coreDisplayTiddlers=Story.prototype.displayTiddlers;
Story.prototype.displayTiddlers = function() {
// suspend single-page mode (and/or top/bottom display options) when showing multiple tiddlers
var opt=config.options;
var saveSPM=opt.chkSinglePageMode; opt.chkSinglePageMode=false;
var saveTPM=opt.chkTopOfPageMode; opt.chkTopOfPageMode=false;
var saveBPM=opt.chkBottomOfPageMode; opt.chkBottomOfPageMode=false;
this.SPM_coreDisplayTiddlers.apply(this,arguments);
opt.chkBottomOfPageMode=saveBPM;
opt.chkTopOfPageMode=saveTPM;
opt.chkSinglePageMode=saveSPM;
}
//}}}
Dal paradosso di Zeno alla somma della serie geometrica
Achille, la tartaruga e la serie geometrica
<<slideShow noClicks forceRefresh>> - A simple slide show that keeps the TW style
<<slideShow style:'MySSStyleSheet' clock:'+'>> - A themed slide show with a clock showing the presentation elapsed time
<<slideShow repeat clock:'-20'>> - A looping slide show with a 20 minutes countdown clock
<<slideShow slidePause:1000>> - A timed slideshow that runs once
<<slideShow slidePause:1000 repeat>> - A timed looping slideshow
-s-
!The [[SlideShowPlugin]]
Press F11 to go fullscreen and adjust the font sizes with Ctrl++ Ctrl+- (or Ctrl+mousewheel).
This plugin was developed by Paulo Soares and Clint Checketts.
{{Comment{This block is not shown in the slide show.
@@Don't show me!!!@@}}}
-s-
!How slides are separated
In a tiddler, you start each slide with the markup {{{-s-}}}
-s-
Slides don't have to have titles like this poor one
-s-
!A slide with subsections and a long title
Check to TOC below to see how this slide title is abbreviated.
!!Section 1
This is a section
!!!Subsection 1.1
This is a subsection
!!!Subsection 1.2
This is another subsection
!!!!Subsubsection 1.2.1
This is a subsubsection
-s-
!Using the keyboard
The following keys are defined:
*Left arrow - previous overlay
*Down arrow - previous slide
*Right arrow - next overlay
*Up arrow - next slide
*Home - first slide
*End - last slide
*Escape - exit slide show
*Spacebar - pause/resume slide show in auto advance mode
-s-
!Slide show parameters
*The slide show can be themed by providing a ~StyleSheet ({{{<<slideShow style:'MyStyleSheet'>>}}})
*By default, there is a clock at bottom of the browser window that displays the current time. This clock can also show the presentation elapsed time with {{{<<slideShow clock:'+'>>}}} or a countdown clock with {{{<<slideShow clock:'-20'>>}}} (for 20 minutes). In these two cases, if you click on the clock display it will be restarted
*The slide show can be set to loop ({{{<<slideShow repeat>>}}})
*You can set it so each slide changes after X milliseconds ({{{<<slideShow slidePause:X>>}}}) (auto advance mode)
*Use auto start mode to begin the slideshow the moment the tiddler is opened ({{{<<slideShow autostart>>>}}})
*You can disable overlays with {{{<<slideShow noOverlays>>}}}
*These parameters can be mixed and matched in any order: {{{<<slideShow slidePause:1000 repeat>>}}} is the same as {{{<<slideShow repeat slidePause:1000>>}}}
-s-
!Overlays
To see how incremental display works use the left and right mouse buttons.
{{Overlay1{You can}}} {{Overlay2{present things}}} {{Overlay1{in an arbitrary order!!!}}}
{{Overlay3{Its a bit harder with lists but it works:}}}
<html>
<ol>
<li class="Overlay4">First item</li>
<li class="Overlay5">Second item</li>
<li class="Overlay4">Last item</li>
</ol>
</html>
{{Comment{You can hide comments on a slide that won't display in the slide show}}}
/***
|''Name:''|SlideShowPlugin|
|''Description:''|Creates a simple slide show type display|
|''Version:''|1.6|
|''Date:''|Feb 12, 2008|
|''Source:''|http://www.math.ist.utl.pt/~psoares/addons.html|
|''Documentation:''|[[SlideShowPlugin Documentation|SlideShowPluginDoc]]|
|''Author:''|Paulo Soares and [[Clint Checketts|http://www.checkettsweb.com]]|
|''License:''|[[Creative Commons Attribution-Share Alike 3.0 License|http://creativecommons.org/licenses/by-sa/3.0/]]|
|''~CoreVersion:''|2.1.0|
***/
//{{{
config.macros.slideShow = {label: "slide show", maxTOCLength: 30};
config.macros.slideShow.messages = {gotoLabel: "Go to slide:"};
config.views.wikified.slideShow = {text: "slide show", tooltip: "Start slide show"};
config.views.wikified.slideShow.quit = {text: "end", tooltip: "Quit the slide show"};
config.views.wikified.slideShow.firstSlide = {text: "<<", tooltip: "first slide"};
config.views.wikified.slideShow.previousSlide = {text: "<", tooltip: "previous slide"};
config.views.wikified.slideShow.nextSlide = {text: ">", tooltip: "next slide"};
config.views.wikified.slideShow.lastSlide = {text: ">>", tooltip: "last slide"};
config.views.wikified.slideShow.resetClock = {text: " ", tooltip: "reset"};
config.formatters.push( {
name: "SlideSeparator",
match: "^-s-+$\\n?",
handler: function(w) {
createTiddlyElement(w.output,"hr",null,'slideSeparator');
}
});
function changeStyleSheet(tiddlerName) {
setStylesheet(store.getRecursiveTiddlerText("StyleSheetColors"),"StyleSheetColors");
setStylesheet(store.getRecursiveTiddlerText("StyleSheetLayout"),"StyleSheetLayout");
setStylesheet(store.getRecursiveTiddlerText(tiddlerName == null ? "StyleSheet" : tiddlerName,""),"StyleSheet");
}
//Excellent (and versatile) reparser created by Paul Petterson for parsing the paramString in a macro
function reparse( params ) {
var re = /([^:\s]+)(?:\:((?:\d+)|(?:["'](?:[^"']+)["']))|\s|$)/g;
var ret = new Array();
var m;
while( (m = re.exec( params )) != null ) ret[ m[1] ] = m[2]?m[2]:true;
return ret;
}
function getElementsByClass(searchClass,node,tag) {
var classElements = new Array();
if ( node == null ) node = document;
if ( tag == null ) tag = '*';
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
var j=0;
for (var i = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}
// 'keys' code adapted from S5 which in turn was adapted from MozPoint (http://mozpoint.mozdev.org/)
function keys(key) {
with(config.macros.slideShow){
if (document.getElementById('contentWrapper').className == "slideShowMode"){
if (!key) {
key = event;
key.which = key.keyCode;
}
switch (key.which) {
case 32: // spacebar
if(time>0){
if(autoAdvance){
clearInterval(autoAdvance);
autoAdvance = null;
} else {
autoAdvance=setInterval("GoToSlide(1)", time);
}
}
break;
case 34: // page down
case 39: // rightkey
GoToSlide("n");
break;
case 40: // downkey
GoToSlide(-1);
break;
case 33: // page up
case 37: // leftkey
GoToSlide("p");
break;
case 38: // upkey
GoToSlide(1);
break;
case 36: // home
GoToSlide("f");
break;
case 35: // end
GoToSlide("l");
break;
case 27: // escape
endSlideShow();
break;
case 66: // B
blankScreen();
break;
}
}
return false;
}
}
function blankScreen(){
var blanker = document.getElementById('slideBlanker');
if (blanker.style.display == 'block'){
blanker.style.display = 'none';
} else {
blanker.style.display = 'block';
}
}
function clicker(e) {
if (!e) var e = window.event;
var target = resolveTarget(e);
//Whenever something is clicked that won't advance the slide make sure that the table of contents gets hidden
if (target.getAttribute('href') != null || isParentOrSelf(target, 'toc') || isParentOrSelf(target,'embed') || isParentOrSelf(target,'object') || isParentOrSelf(target, 'slideFooter') || isParentOrSelf(target, 'navigator')){
//Don't hide the TOC if the indexNumbers (which trigger the index) is clicked
if(isParentOrSelf(target,'indexNumbers') || isParentOrSelf(target,'jumpInput')){
return true;
}
showHideTOC('none');
return true;
}
//Advance a slide if the TOC is visible otherwise make sure that the TOC gets hidden
if ((!e.which && e.button == 1) || e.which == 1) {
if (document.getElementById('toc').style.display != 'block'){
GoToSlide("n");
} else {
showHideTOC('none');
}
}
if ((!e.which && e.button == 2) || e.which == 3) {
if (document.getElementById('toc').style.display != 'block'){
GoToSlide("p");
} else {
showHideTOC('none');
}
return false;
}
}
function isParentOrSelf(element, id) {
if (element == null || element.nodeName=='BODY') return false;
else if (element.id == id) return true;
else return isParentOrSelf(element.parentNode, id);
}
GoToSlide = function(step) {
var new_pos;
var slideHolder = document.getElementById('slideContainer');
//The parse float ensures that the attribute is returned as a number and not a string.
var cur_pos = parseFloat(slideHolder.getAttribute('currentslide'));
var numberSlides = parseFloat(slideHolder.getAttribute('numberSlides'));
switch (step) {
case "f":
new_pos=0;
break;
case "l":
new_pos=numberSlides-1;
break;
case "n":
var numberOverlays = parseFloat(slideHolder.childNodes[cur_pos].getAttribute('numberOverlays'));
var currentOverlay = parseFloat(slideHolder.getAttribute('currentOverlay'));
if(numberOverlays==0 || currentOverlay==numberOverlays){
if(noClicks==false) new_pos=cur_pos+1;
} else {
var className="Overlay"+currentOverlay;
var overlay=getElementsByClass(className,slideHolder.childNodes[cur_pos]);
for(var i=0; i<overlay.length; i++) {overlay[i].className=className+' previousOverlay';}
currentOverlay++;
slideHolder.setAttribute('currentOverlay',currentOverlay);
className="Overlay"+currentOverlay;
overlay=getElementsByClass(className,slideHolder.childNodes[cur_pos]);
for(i=0; i<overlay.length; i++) {overlay[i].className=className+' currentOverlay';}
return false;
}
break;
case "p":
var numberOverlays = parseFloat(slideHolder.childNodes[cur_pos].getAttribute('numberOverlays'));
var currentOverlay = parseFloat(slideHolder.getAttribute('currentOverlay'));
if(numberOverlays==0 || currentOverlay==0){
if(noClicks==false) new_pos=cur_pos-1;
} else {
var className="Overlay"+currentOverlay;
var overlays=getElementsByClass(className,slideHolder.childNodes[cur_pos]);
for(var i=0; i<overlays.length; i++) {overlays[i].className=className+' nextOverlay';}
currentOverlay--;
className="Overlay"+currentOverlay;
overlays=getElementsByClass(className,slideHolder.childNodes[cur_pos]);
for(i=0; i<overlays.length; i++) {overlays[i].className=className+' currentOverlay';}
slideHolder.setAttribute('currentOverlay',currentOverlay);
return false;
}
break;
default:
new_pos=cur_pos+step;
}
if(slideShowCircularMode && new_pos == numberSlides) new_pos=0;
if(slideShowCircularMode && new_pos<0) new_pos=(numberSlides - 1);
if(step!=0 && new_pos>=0 && new_pos<numberSlides) {
slideHolder.childNodes[cur_pos].style.display='none';
slideHolder.childNodes[new_pos].style.display='block';
slideHolder.setAttribute('currentslide',new_pos);
var numberOverlays = parseFloat(slideHolder.childNodes[new_pos].getAttribute('numberOverlays'));
if(step=="p"){
var currentOverlay=numberOverlays;
var state=' previousOverlay';
} else {
var currentOverlay=0;
var state=' nextOverlay';
}
slideHolder.setAttribute('currentOverlay',currentOverlay);
if(numberOverlays>0) {
for(var i=1; i<=numberOverlays; i++){
var className="Overlay"+i;
var overlays=getElementsByClass(className,slideHolder.childNodes[new_pos]);
for(var j=0; j<overlays.length; j++) {overlays[j].className=className+state;}
}
if(step=="p"){
var className="Overlay"+numberOverlays;
var overlays=getElementsByClass(className,slideHolder.childNodes[new_pos]);
for(var j=0; j<overlays.length; j++) {overlays[j].className=className+' currentOverlay';}
}
}
new_pos++;
var indexNumbers = document.getElementById('indexNumbers');
indexNumbers.firstChild.data = new_pos+'/'+numberSlides;
if((new_pos==numberSlides) && !slideShowCircularMode && autoAdvance) clearInterval(autoAdvance);
return true;
}
return false;
}
function tocShowSlide(e) {
if (!e) var e = window.event;
var target = resolveTarget(e);
var slide = target.getAttribute('slideNumber');
var cur_pos = document.getElementById('slideContainer').getAttribute('currentslide');
var step = slide-cur_pos;
if(step!=0) GoToSlide(step);
showHideTOC('none');
return;
}
//Toggle the display of the table of contents
function showHideTOC(display){
var toc = document.getElementById('toc');
//Reset the input box
document.getElementById('jumpInput').value = "";
if (display == null || display.length == null){
if (toc.style.display == 'none' || toc.style.display == ''){
toc.style.display = 'block';
document.getElementById('jumpInput').focus();
} else {
toc.style.display = 'none';
}
} else {
toc.style.display = display;
if (display == 'block')
document.getElementById('jumpInput').focus();
}
}
function padZero(x){return (x>=10 || x<0 ? "" : "0")+x;}
setClock = function(){
var actualTime = new Date();
var newTime = actualTime.getTime() - clockStartTime;
newTime = clockMultiplier*newTime+clockInterval+clockCorrection;
actualTime.setTime(newTime);
newTime = padZero(actualTime.getHours()) + ":" + padZero(actualTime.getMinutes());
//+ ":" + padZero(actualTime.getSeconds());
var clock = document.getElementById('slideClock');
clock.firstChild.nodeValue = newTime;
}
function resetClock(){
var time = new Date(0);
if(clockStartTime>time){
var startTime = new Date();
clockStartTime=startTime.getTime();
}
}
var title;
var place;
var autoAdvance=null;
var slideClock=null;
var noOverlays=false;
var noClicks=false;
var forceRefresh=false;
var time = 0;
var slideShowCircularMode;
var slideShowStyleSheet;
var slideShowParams;
var clockMultiplier;
var clockInterval;
var clockCorrection=0;
var clockStartTime;
var openTiddlers;
config.macros.slideShow.handler = function(aPlace,macroName,params,wikifier,paramString,tiddler){
if(tiddler instanceof Tiddler){
var lingo = config.views.wikified.slideShow;
if (!e) var e = window.event;
place = aPlace;
title = tiddler.title;
params = reparse(paramString);
var onclick = function(){config.macros.slideShow.onClickSlideShow(params);};
createTiddlyButton(aPlace,lingo.text,lingo.tooltip,onclick);
}
}
config.macros.slideShow.onClickSlideShow = function(newParams) {
// if(typeof(newParams)=="number") newParams=slideShowParams;
openTiddlers = new Array;
var viewer=document.getElementById('tiddlerDisplay');
for(var i=0; i<viewer.childNodes.length; i++){
var name = viewer.childNodes[i].getAttribute('tiddler');
openTiddlers.push(name);
}
document.oncontextmenu = function(e){return false;}
clockMultiplier = 1;
clockInterval = 0;
var startTime = new Date(0);
slideShowCircularMode = false;
time = 0;
slideShowStyleSheet = null;
if(newParams['style']){
slideShowStyleSheet = eval(newParams['style']);
}
if(newParams['repeat']){
slideShowCircularMode = true;
}
if(newParams['noClicks']){
noClicks = true;
}
if(newParams['forceRefresh']){
forceRefresh = true;
}
if(newParams['slidePause'] > 0){
time = newParams['slidePause'];
}
if(newParams['clock']){
clockCorrection=startTime.getTimezoneOffset()*60000;
startTime = new Date();
var clockType= eval(newParams['clock']);
if(clockType != '+') {
clockMultiplier = -1;
clockInterval = -clockType*60000;
}
}
clockStartTime=startTime.getTime();
if(newParams['noOverlays']){
noOverlays = true;
}
clearMessage();
//Attach the key and mouse listeners
document.onkeyup = keys;
document.onmouseup = clicker;
story.refreshTiddler(title,"SlideShowViewTemplate",true);
createSlides(newParams);
slideClock=setInterval('setClock()', 1000);
if(time>0) autoAdvance=setInterval("GoToSlide(1)", time);
story.closeAllTiddlers(title);
toggleSlideStyles();
return;
}
config.macros.slideShow.endSlideShow=function(){
var showHolder = document.getElementById('slideShowWrapper');
showHolder.parentNode.removeChild(showHolder);
document.oncontextmenu = function(e){};
if(autoAdvance) clearInterval(autoAdvance);
if(slideClock) clearInterval(slideClock);
noClicks=false;
story.refreshTiddler(title,null,true);
story.closeAllTiddlers();
toggleSlideStyles();
story.displayTiddlers(null,openTiddlers,DEFAULT_VIEW_TEMPLATE);
document.onmouseup = function(){};
}
function isInteger(s){
var i;
for (i = 0; i < s.length; i++){
// Check that current character is number.
var c = s.charAt(i);
if (((c < "0") || (c > "9"))) return false;
}
// All characters are numbers.
return true;
}
function jumpInputToSlide(e){
if (!e) {
e = window.event;
e.which = e.keyCode;
}
if(e.which==13){
var jumpInput= document.getElementById("jumpInput").value;
if(isInteger(jumpInput)){
var step=jumpInput-document.getElementById('slideContainer').getAttribute('currentslide')-1;
if (GoToSlide(step)){
showHideTOC('none');
}
}
}
return;
}
//Used to shorten the TOC fields
function abbreviateLabel(label){
var maxTOCLength = config.macros.slideShow.maxTOCLength;
if(label.length>maxTOCLength) {
var temp = new Array();
temp = label.split(' ');
label = temp[0];
for(var j=1; j<temp.length; j++){
if((label.length+temp[j].length)<=maxTOCLength){
label += " " + temp[j];
} else {
label += " ...";
break;
}
}
}
return label;
}
function createSlides(newParams){
var lingo = config.views.wikified.slideShow;
//Remove dblClick on edit function
var theTiddler = document.getElementById("tiddler"+title);
theTiddler.ondblclick = function() {};
// Grab the 'viewer' element and give it a signature so the show can be resumed if stopped
var tiddlerElements = theTiddler.childNodes;
var viewer;
for (var i = 0; i < tiddlerElements.length; i++){
if (tiddlerElements[i].className == "viewer") viewer = tiddlerElements[i];
}
viewer.id = 'slideShowWrapper';
//Hide the text that comes before the first H1 element (I think I may put this into a cover page type thing)
while(viewer.childNodes.length > 0 && viewer.firstChild.nodeName.toUpperCase() != "HR" && viewer.firstChild.className!="slideSeparator") {
viewer.removeChild(viewer.firstChild);
}
//Cycle through the content and each time you hit an H1 begin a new slide div
var slideNumber = 0;
var slideHolder = document.createElement('DIV');
slideHolder.id = "slideContainer";
slideHolder.setAttribute('currentslide',0);
while(viewer.childNodes.length > 0){
//Create a new slide a append it to the slide holder
if (viewer.firstChild.nodeName.toUpperCase() == "HR" && viewer.firstChild.className=="slideSeparator"){
slideNumber++;
var slide = document.createElement('DIV');
slide.id = "slideNumber"+slideNumber;
slide.className = "slide";
if (slideNumber > 1) {
//slideHolder.setAttribute('currentslide',0);
slide.style.display='none';
} else {
slide.style.display='block';
}
slideHolder.appendChild(slide);
viewer.removeChild(viewer.firstChild);
} else {
if(viewer.firstChild.nodeName=="SPAN" && viewer.firstChild.className=="" && viewer.firstChild.hasChildNodes()) {
var anchor=viewer.firstChild.nextSibling;
for (var ii=0;ii<viewer.firstChild.childNodes.length;ii++) {
var clone=viewer.firstChild.childNodes[ii].cloneNode(true);
viewer.insertBefore(clone,anchor);
}
viewer.removeChild(viewer.firstChild);
} else {
slide.appendChild(viewer.firstChild);
}
}
}
//Stick the slides back into the viewer
var blanker= createTiddlyElement(viewer,"DIV","slideBlanker");
blanker.style.display="none";
viewer.appendChild(slideHolder);
slideHolder.setAttribute('numberSlides',slideNumber);
//Create the navigation bar
var slidefooter = createTiddlyElement(viewer,"DIV","slideFooter","slideFooterOff");
var navigator = createTiddlyElement(slidefooter,"SPAN","navigator");
//Make it so that when the footer is hovered over the class will change to make it visible
slidefooter.onmouseover = function () {slidefooter.className = "slideFooterOn"};
slidefooter.onmouseout = function () {slidefooter.className = "slideFooterOff"};
//Create the control button for the navigation
var onClickQuit = function(){config.macros.slideShow.endSlideShow();};
createTiddlyButton(navigator,lingo.quit.text,lingo.quit.tooltip,onClickQuit);
createTiddlyButton(navigator,lingo.firstSlide.text,lingo.firstSlide.tooltip,first_slide);
createTiddlyButton(navigator,lingo.previousSlide.text,lingo.previousSlide.tooltip,previous_slide);
createTiddlyButton(navigator,lingo.nextSlide.text,lingo.nextSlide.tooltip,next_slide);
createTiddlyButton(navigator,lingo.lastSlide.text,lingo.lastSlide.tooltip,last_slide);
createTiddlyButton(navigator,lingo.resetClock.text,lingo.resetClock.tooltip,resetClock,"button","slideClock");
var indexNumbers = createTiddlyElement(slidefooter,"SPAN","indexNumbers","indexNumbers","1/"+slideNumber)
indexNumbers.onclick = showHideTOC;
var toc = createTiddlyElement(slidefooter,"UL","toc");
var ovl=1;
for (var i=0;i<slideHolder.childNodes.length;i++) {
if(!noOverlays) {
var ovl=1;
while(1){
var className="Overlay"+ovl;
var overlays=getElementsByClass(className,slideHolder.childNodes[i]);
if(overlays.length>0){
for(var j=0; j<overlays.length; j++) {overlays[j].className+=' nextOverlay';}
ovl++;
} else {break;}
}
}
slideHolder.childNodes[i].setAttribute("numberOverlays",ovl-1);
slideHolder.setAttribute("currentOverlay",0);
//Loop through each slide and check the header's content
var tocLabel = null;
for (var j=0;j<slideHolder.childNodes[i].childNodes.length;j++) {
var node = slideHolder.childNodes[i].childNodes[j];
if(node.nodeName=="H1" || node.nodeName=="H2" || node.nodeName=="H3" || node.nodeName=="H4") {
var htstring = node.innerHTML;
var stripped = htstring.replace(/(<([^>]+)>)/ig,"");
tocLabel = abbreviateLabel(stripped);
var tocLevel="tocLevel"+node.nodeName.charAt(1);
var tocItem = createTiddlyElement(toc,"LI",null,tocLevel);
var tocLink = createTiddlyElement(tocItem,"A",null,"tocItem",tocLabel);
tocLink.setAttribute("slideNumber",i);
tocLink.onclick=tocShowSlide;
}
}
}
//Input box to jump to s specific slide
var tocItem = createTiddlyElement(toc,"LI",null,"tocJumpItem",config.macros.slideShow.messages.gotoLabel);
var tocJumpInput = createTiddlyElement(tocItem,"INPUT","jumpInput");
tocJumpInput.type="text";
tocJumpInput.onkeyup=jumpInputToSlide;
}
var next_slide= function(e){GoToSlide(1);}
var first_slide= function(e){GoToSlide("f");}
var previous_slide= function(e){GoToSlide(-1);}
var last_slide= function(e){GoToSlide("l");}
function toggleSlideStyles(){
var contentWrapper = document.getElementById('contentWrapper');
if (contentWrapper.className == "slideShowMode"){
contentWrapper.className = "";
refreshPageTemplate();
setStylesheet("#backstageShow{display: block;}","SlideShowStyleSheet");
changeStyleSheet();
} else{
contentWrapper.className = "slideShowMode";
refreshPageTemplate("SlideShowPageTemplate");
setStylesheet(store.getRecursiveTiddlerText("SlideShowStyleSheet"),"SlideShowStyleSheet");
if(slideShowStyleSheet) changeStyleSheet(slideShowStyleSheet);
}
}
config.shadowTiddlers.SlideShowPageTemplate="<!--{{{-->\n<div id='displayArea'>\n<div id='tiddlerDisplay'></div>\n</div>\n<!--}}}-->";
config.shadowTiddlers.SlideShowViewTemplate="<!--{{{-->\n<div class='title' macro='view title'></div>\n<div class='viewer' macro='view text wikified'></div>\n<!--}}}-->";
config.shadowTiddlers.SlideShowStyleSheet = "/***\n!Slide Mode Styles\n***/\n/*{{{*/\n#slideBlanker {\n position:absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n z-index: 90; \n background-color: #000;\n}\n#backstageShow{\n display: none !important;\n}\n\n#contentWrapper.slideShowMode #slideContainer{\n display: block;\n}\n\n#contentWrapper.slideShowMode .Comment{\n display: none;\n}\n\n#contentWrapper.slideShowMode .nextOverlay{\n visibility: hidden;\n}\n\n#contentWrapper.slideShowMode .currentOverlay{\n visibility: visible;\n}\n\n#contentWrapper.slideShowMode .previousOverlay{\n visibility: visible;\n}\n\n#jump{\n text-align: right;\n}\n\n.slideFooterOff #navigator{\n visibility: hidden;\n}\n\n.slideFooterOn #navigator{\n visibility: visible;\n}\n\n#contentWrapper.slideShowMode #slideClock{\n cursor: pointer; margin: 0 5px 0 5px; border: 1px solid #db4\n}\n\n#contentWrapper.slideShowMode,\n #contentWrapper.slideShowMode #displayArea{\n width: 100%;\n font-size: 1.5em;\n margin: 0 !important;\n padding: 0;\n}\n\n#slideContainer{\n display: none;\n}\n\n.indexNumbers{\n cursor: pointer;\n}\n\n#navigator{\n visibility: hidden;\n bottom: 0;\n}\n\n#toc{\n display: none;\n position: absolute;\n font-size: .75em;\n bottom: 2em;\n right: 0;\n background: #fff;\n border: 1px solid #000;\n text-align: left;\n}\n\nul#toc, #toc li{\n margin: 0;\n padding: 0;\n list-style: none;\n line-height: 1em;\n}\n\n.tocJumpItem{\n margin-right: 2em;\n}\n\n.tocJumpItem input{\nmargin-right: 1em;\n border: 0;\n}\n\n#toc a,\n#toc a.button{\n display: block;\n padding: .1em;\n}\n\n#toc .tocLevel1{\nfont-size: .8em;\n}\n\n#toc .tocLevel2{\n margin-left: 1em;\n font-size: .75em;\n}\n\n#toc .tocLevel3{\n margin-left: 2em;\nfont-size: .75em;\n}\n\n#toc .tocLevel4{\n margin-left: 3em;\nfont-size: .65em;\n}\n\n#toc a{\n cursor: pointer;\n}\n\nh1{\n min-height: 1em;\n}\n\n.slide h1{\n min-height: 0;\n}\n\n/* The '>' selector is ignored by IE6 and earlier so the proper rules are given */\n#slideFooter{\n position: fixed;\n bottom: 2px;\n right: 2px;\n width: 100%;\n text-align: right;\n}\n\n/* This is a hack to trick IE6 and earlier to put the navbar on the bottom of the page */\n* html #slideFooter {\n position: absolute;\n width: 100%;\n text-align: right;\n right: auto; bottom: auto;\n left: expression( ( -20 - slideFooter.offsetWidth + ( document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth ) + ( ignoreMe2 = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ) ) + 'px' );\n top: expression( ( -10 - slideFooter.offsetHeight + ( document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight ) + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) ) + 'px' );\n}\n\n\n\n/*}}}*/";
config.shadowTiddlers.SlideShowPluginDoc="The documentation is missing. It is available [[here|http://www.math.ist.utl.pt/~psoares/addons.html#SlideShowPluginDoc]].";
//}}}
!Description
This plugin turns a TiddlyWiki tiddler into a simple slide show type display. Most features that are usually found in presentation software are available. It should work in a way that does not interfere with TiddlyWiki. When you close the slide show you get back to your good old TW.
This plugin has been tested in Firefox and Internet Explorer. Let me know if something seems broken.
!Usage
To use this plugin you //must// be using TiddlyWiki 2.0. Some optional features (as the incremental display) require version 2.0.8 or higher. To install the plugin copy the tiddlers SlideShowPlugin, SlideShowPageTemplate and SlideShowViewTemplate to your TW, label the first one with the //systemConfig// tag, save the TW and refresh the browser.
To make a slide show simply drop {{{<<slideShow>>}}} at the beginning of a tiddler and use {{{-s-}}} to start each slide.
If you move your mouse over the bottom of the browser window you will see a few navigation buttons, a clock and a table of contents that shows up when you click the slide number.
Any block of text marked as {{{{{Comment{For my eyes only!}}}}}} will not be displayed in the slide show.
See these and other features in this [[SlideShowExample]].
!Incremental display
A succession of overlays (or layers) can be defined in each slide by marking blocks of text with {{{{{Overlay1{...some text...}}}}}}, {{{{{Overlay2{...some text...}}}}}}, {{{{{Overlay3{...some text...}}}}}}, ...
To costumize the way overlays are shown you can redefine the following CSS classes
*contentWrapper.slideShowMode .previousOverlay
*contentWrapper.slideShowMode .currentOverlay
*contentWrapper.slideShowMode .nextOverlay
in a ~StyleSheet. The default style simply hides the next overlays and shows the current and the previous ones as normal text.
!Slide show parameters
*The slide show can be themed by providing a ~StyleSheet ({{{<<slideShow style:'MyStyleSheet'>>}}})
*By default, there is a clock at bottom of the browser window that displays the current time. This clock can also show the presentation elapsed time with {{{<<slideShow clock:'+'>>}}} or a countdown clock with {{{<<slideShow clock:'-20'>>}}} (for 20 minutes). In these two cases, if you click on the clock display it will be restarted
*The slide show can be set to loop ({{{<<slideShow repeat>>}}})
*You can set it so each slide changes after X milliseconds ({{{<<slideShow slidePause:X>>}}}) (auto advance mode)
*To not use the mouse to navigate through the presentation use {{{<<slideShow noClicks>>>}}}. This is useful when there are clickable elements in the presentation
*{{{<<slideShow forceRefresh>>>}}} forces a refresh of the presentation tiddler (useful when a presentation is built from separate tiddlers using the {{{<<tiddler>>}}} macro)
*Overlays can be disabled with {{{<<slideShow noOverlays>>}}}
*These parameters can be mixed and matched in any order: {{{<<slideShow slidePause:1000 repeat>>}}} is the same as {{{<<slideShow repeat slidePause:1000>>}}}
!Slide show navigation
You can navigate through a slide show using the keyboard or the mouse. To quickly move to titled sections you can use the table of contents.
!!Mouse navigation
Left (right) clicking on a slide jumps to the next (previous) overlay. To move to the beginning of the next or previous slide you must use the navigation bar at the bottom of the browser's window. If there are no overlays defined both operations are equivalent.
!!Keyboard
The following keys are defined:
*Left arrow - previous overlay
*Down arrow - previous slide
*Right arrow - next overlay
*Up arrow - next slide
*Home - first slide
*End - last slide
*Escape - exit slide show
*Spacebar - pause/resume slide show in auto advance mode
*B - blank screen
!Revision history
*1.6
**removed seconds from clock
**added B key to blank screen
**a few fixes to make it work with IE7
*1.5.3
**fix for ~TW2.2
**forceRefresh and noClicks
**removed autoStart feature
**templates are now in shadow tiddlers
*1.5.2 13/02/2007
**fixed a conflict with TW pageFooter
*1.5.1 10/11/2006
**added SlideShowPageTemplate and SlideShowViewTemplate. This way, the plugin no longer requires a standard TW layout. Thanks to Andrew Lister for the idea.
*1.5.0 18/09/2006
**fixed restoring stylesheet on exit
**changed (again!) the way how slides are separated (slide shows prepared for previous versions must be fixed)
*1.4.0 20/04/2006
**changed the way how slides are separated (slide shows prepared for previous versions must be fixed)
**now works with content included with the {{{<<tiddler>>}}} macro
**added incremental display (overlays)
**improved documentation
**assorted small fixes
*1.3.1 10/03/2006
**removed empty slide titles
**fixed wrong numberSlides when slides have div's
**fixed wrong time in Windows
*1.3.0 26/02/2006
**restore open tiddlers on exit
**fixed problem with markup in headers (should work with NestedSlidersPlugin)
**added slide comments (blocks of text in the tiddler that don't show up in the presentation)
*1.2.1 28/01/2006
**pause timed slideshow with spacebar
**added clock with 3 different modes
**fixed bugs with style and abbreviation options
**general cleanup
*1.2.0 07/01/2006
**added a resume feature
**added themes support
*1.1.5 14/12/2005
**added mouse support
**cleaned up navbar generation
*1.1.0 12/12/2005
**added support for IE
**added key listeners
*1.0.0 11/12/2005
**initial release
!Todo
*Time code is still very hackerish and unreliable.
/***
|''Name:''|SparklinePlugin|
|''Description:''|Sparklines macro|
***/
//{{{
if(!version.extensions.SparklinePlugin) {
version.extensions.SparklinePlugin = {installed:true};
//--
//-- Sparklines
//--
config.macros.sparkline = {};
config.macros.sparkline.handler = function(place,macroName,params)
{
var data = [];
var min = 0;
var max = 0;
var v;
for(var t=0; t<params.length; t++) {
v = parseInt(params[t]);
if(v < min)
min = v;
if(v > max)
max = v;
data.push(v);
}
if(data.length < 1)
return;
var box = createTiddlyElement(place,"span",null,"sparkline",String.fromCharCode(160));
box.title = data.join(",");
var w = box.offsetWidth;
var h = box.offsetHeight;
box.style.paddingRight = (data.length * 2 - w) + "px";
box.style.position = "relative";
for(var d=0; d<data.length; d++) {
var tick = document.createElement("img");
tick.border = 0;
tick.className = "sparktick";
tick.style.position = "absolute";
tick.src = "data:image/gif,GIF89a%01%00%01%00%91%FF%00%FF%FF%FF%00%00%00%C0%C0%C0%00%00%00!%F9%04%01%00%00%02%00%2C%00%00%00%00%01%00%01%00%40%02%02T%01%00%3B";
tick.style.left = d*2 + "px";
tick.style.width = "2px";
v = Math.floor(((data[d] - min)/(max-min)) * h);
tick.style.top = (h-v) + "px";
tick.style.height = v + "px";
box.appendChild(tick);
}
};
}
//}}}
/*{{{*/
/*Mocha TiddlyWiki Theme*/
/*Version 1.0*/
/*Design and CSS originally by Anthonyy, ported to TiddlyWiki by Saq Imtiaz.*/
/*}}}*/
/*{{{*/
#contentWrapper{
margin: 0 3.4em;
font-family: Lucida Grande, Tahoma, Arial, Helvetica, sans-serif; /* Lucida Grande for the Macs, Tahoma for the PCs */
font-size: 11px;
line-height: 1.6em;
color: #666;
}
.header {
background: #fff;
padding-top: 10px;
clear: both;
border-bottom: 4px solid #948979;
}
.headerShadow { padding: 2.6em 0em 0.5em 0em; }
.siteTitle {
font-family: 'Trebuchet MS' sans-serif;
font-weight: bold;
font-size: 32px;
color: #CC6633;
margin-bottom: 30px;
background-color: #FFF;
}
.siteTitle a{color:#CC6633; border-bottom:1px dotted #cc6633;}
.siteSubtitle {
font-size: 1.0em;
display: block;
margin: .5em 3em; color: #999999;
}
#mainMenu {
position:relative;
float:left;
margin-bottom:1em;
display:inline;
text-align:left;
padding: 2em 0.5em 0.5em 0em;
width:13em;
font-size:1em;
}
#sidebar{
position:relative;
float:right;
margin-bottom:1em;
padding-top:2em;
display:inline;
}
#displayArea {
margin: 0em 17em 0em 15em;
}
.tagClear {clear:none;}
#contentFooter {background:#575352; color:#BFB6B3; clear: both; padding: 0.5em 1em;}
#contentFooter a {
color: #BFB6B3;
border-bottom: 1px dotted #BFB6B3;
}
#contentFooter a:hover {
color: #FFFFFF;
background-color:#575352;
}
a,#sidebarOptions .sliderPanel a{
color:#CC6714;
text-decoration: none;
}
a:hover,#sidebarOptions .sliderPanel a:hover {
color:#CC6714;
background-color: #F5F5F5;
}
.viewer .button, .editorFooter .button{
color: #666;
border: 1px solid #CC6714;
}
.viewer .button:hover,
.editorFooter .button:hover{
color: #fff;
background: #CC6714;
border-color: #CC6714;
}
.viewer .button:active, .viewer .highlight,.editorFooter .button:active, .editorFooter .highlight{color:#fff; background:#575352;border-color:#575352;}
#mainMenu a {
display: block;
padding: 5px;
border-bottom: 1px solid #CCC;
}
#mainMenu a:link, #navlist a:visited {
color:#CC6714;
text-decoration: none;
}
#mainMenu a:hover {
background: #000000 url(arrow.gif) 96% 50% no-repeat;
background-color: #F5F5F5;
color:#CC6714;
}
#mainMenu a:hover, #mainMenu a:active, #mainMenu .highlight, #mainMenu .marked {
background: #000000 url(arrow.gif) 96% 50% no-repeat;
background-color: #F5F5F5;
color:#CC6714;
}
#mainMenu span {position:relative;}
#mainMenu br {display:none;}
#sidebarOptions a {
color:#999;
text-decoration: none;
}
#sidebarOptions a:hover {
color:#4F4B45;
background-color: #F5F5F5;border:1px solid #fff;
}
#sidebarOptions {line-height:1.4em;}
.tiddler {
padding-bottom: 40px;
border-bottom: 1px solid #DDDDDD;
}
.title {color:#CC6633;}
.subtitle, .subtitle a { color: #999999; font-size:0em;margin:0.2em;}
.shadow .title{color:#948979;}
.selected .toolbar a {color:#999999;}
.selected .toolbar a:hover {color:#4F4B45; background:transparent;border:1px solid #fff;}
.toolbar .button:hover, .toolbar .highlight, .toolbar .marked, .toolbar a.button:active{color:#4F4B45; background:transparent;border:1px solid #fff;}
.toolbar{;}
.listLink,#sidebarTabs .tabContents {line-height:1.5em;}
.listTitle {color:#888;}
#sidebarTabs .tabContents {background:#fff;}
#sidebarTabs .tabContents .tiddlyLink, #sidebarTabs .tabContents .button{color:#999;}
#sidebarTabs .tabContents .tiddlyLink:hover,#sidebarTabs .tabContents .button:hover{color:#4F4B45;background:#fff}
#sidebarTabs .tabContents .button:hover, #sidebarTabs .tabContents .highlight, #sidebarTabs .tabContents .marked, #sidebarTabs .tabContents a.button:active{color:#4F4B45;background:#fff}
.tabSelected{color:#fff; background:#948979;}
.tabUnselected {
background: #ccc;
}
.tabSelected, .tabSelected:hover {
color: #fff;
background: #948979;
border: solid 1px #948979;
padding-bottom:1px;
}
.tabUnselected {
color: #999;
background: #eee;
border: solid 1px #ccc;
padding-bottom:1px;
}
#sidebarTabs .tabUnselected { border-bottom: none;padding-bottom:3px;}
#sidebarTabs .tabSelected{padding-bottom:3px;}
#sidebarTabs .tabUnselected:hover { border-bottom: none;padding-bottom:3px;color:#4F4B45}
#sidebarOptions .sliderPanel {
background: #fff; border:none;
font-size: .9em;
}
#sidebarOptions .sliderPanel a {font-weight:normal;}
#sidebarOptions .sliderPanel input {border:1px solid #999;}
.viewer blockquote {
border-left: 3px solid #948979;
}
.viewer table {
border: 2px solid [[ColorPalette::TertiaryDark]];
}
.viewer th, thead td {
background: #948979;
border: 1px solid #948979;
color: #fff;
}
.viewer pre {
border: 1px solid #948979;
background: #f5f5f5;
}
.viewer code {
color: #2F2A29;
}
.viewer hr {
border-top: dashed 1px #948979;
}
.editor input {
border: 1px solid #948979;
}
.editor textarea {
border: 1px solid #948979;
}
.popup {
background: #948979;
border: 1px solid #948979;
}
.popup li.disabled {
color: #000;
}
.popup li a, .popup li a:visited {
color: #eee;
border: none;
}
.popup li a:hover {
background: #575352;
color: #fff;
border: none;
}
.tagging, .tagged {
border: 1px solid #eee;
background-color: #F7F7F7;
}
.selected .tagging, .selected .tagged {
background-color: #eee;
border: 1px solid #BFBAB3;
}
.tagging .listTitle, .tagged .listTitle {
color: #bbb;
}
.selected .tagging .listTitle, .selected .tagged .listTitle {
color: #666;
}
.tagging .button, .tagged .button {
color:#aaa;
}
.selected .tagging .button, .selected .tagged .button {
color:#4F4B45;
}
.highlight, .marked {background:transparent; color:#111; border:none; text-decoration:underline;}
.tagging .button:hover, .tagged .button:hover, .tagging .button:active, .tagged .button:active {
border: none; background:transparent; text-decoration:underline; color:#000;
}
h1,h2,h3,h4,h5 { color: #666; background: transparent; padding-bottom:2px; font-family: Arial, Helvetica, sans-serif; }
h1 {font-size:18px;}
h2 {font-size:16px;}
h3 {font-size: 14px;}
#messageArea {
border: 4px solid #948979;
background: #f5f5f5;
color: #999;
font-size:90%;
}
#messageArea a:hover { background:#f5f5f5;}
#messageArea .button{
color: #666;
border: 1px solid #CC6714;
}
#messageArea .button:hover {
color: #fff;
background: #948979;
border-color: #948979;
}
* html .viewer pre {
margin-left: 0em;
}
* html .editor textarea, * html .editor input {
width: 98%;
}
.searchBar {float:right;font-size: 1.0em;}
.searchBar .button {color:#999;display:block;}
.searchBar .button:hover {border:1px solid #fff;color:#4F4B45;}
.searchBar input {
background-color: #FFF;
color: #999999;
border: 1px solid #CCC; margin-right:3px;
}
#sidebarOptions .button:active, #sidebarOptions .highlight {background:#F5F5F5;}
*html #contentFooter { padding:0.25em 1em 0.5em 1em;}
#noticeBoard {font-size: 0.9em; color:#999; position:relative;display:block;background:#fff; clear: both; margin-right:0.5em; margin-top:60px; padding:5px; border-bottom: 1px dotted #CCC; border-top: 1px dotted #CCC;}
#mainMenu #noticeBoard a,#mainMenu #noticeBoard .tiddlyLink {display:inline;border:none;padding:5px 2px;color:#DF9153 }
#noticeBoard a:hover {border:none;}
#noticeBoard br {display:inline;}
#mainMenu #noticeBoard .button{
color: #666;
border: 1px solid #DF9153;padding:2px;
}
#mainMenu #noticeBoard .button:hover{
color: #fff;
background: #DF9153;
border-color: #DF9153;
}
.searchbar {position:relative; width:11em;}
.searchbar .button{margin:0; width:11em;}
#header {display:inline-block;}
/*}}}*/
<<formTiddler NewPluginTemplate>><data>{"category":"Toggling page elements","author":"Eric Shulman (~TiddlyTools)","link":"http://www.tiddlytools.com","format":"Script","description":"Dynamically enable/disable BreadcrumbsPlugin display.","twversion":"--"}</data>
<<formTiddler NewPluginTemplate>><data>{"author":"Eric Shulman (~TiddlyTools)","link":"http://www.tiddlytools.com","twversion":"2.1","format":"Script","category":"Toggling page elements","description":"Show/hide left sidebar (MainMenu)"}</data>
/***
|Name|ToggleSideBarMacro|
|Created by|SaqImtiaz|
|Location|http://tw.lewcid.org/#ToggleSideBarMacro|
|Version|1.0|
|Requires|~TW2.x|
!Description:
Provides a button for toggling visibility of the SideBar. You can choose whether the SideBar should initially be hidden or displayed.
!Demo
<<toggleSideBar "Toggle Sidebar">>
!Usage:
{{{<<toggleSideBar>>}}} <<toggleSideBar>>
additional options:
{{{<<toggleSideBar label tooltip show/hide>>}}} where:
label = custom label for the button,
tooltip = custom tooltip for the button,
show/hide = use one or the other, determines whether the sidebar is shown at first or not.
(default is to show the sidebar)
You can add it to your tiddler toolbar, your MainMenu, or where you like really.
If you are using a horizontal MainMenu and want the button to be right aligned, put the following in your StyleSheet:
{{{ .HideSideBarButton {float:right;} }}}
!History
*23-07-06: version 1.0: completely rewritten, now works with custom stylesheets too, and easier to customize start behaviour.
*20-07-06: version 0.11
*27-04-06: version 0.1: working.
!Code
***/
//{{{
config.macros.toggleSideBar={};
config.macros.toggleSideBar.settings={
styleHide : "#sidebar { display: none;}\n"+"#contentWrapper #displayArea { margin-right: 1em;}\n"+"",
styleShow : " ",
arrow1: "«",
arrow2: "»"
};
config.macros.toggleSideBar.handler=function (place,macroName,params,wikifier,paramString,tiddler)
{
var tooltip= params[1]||'toggle sidebar';
var mode = (params[2] && params[2]=="hide")? "hide":"show";
var arrow = (mode == "hide")? this.settings.arrow1:this.settings.arrow2;
var label= (params[0]&¶ms[0]!='.')?params[0]+" "+arrow:arrow;
var theBtn = createTiddlyButton(place,label,tooltip,this.onToggleSideBar,"button HideSideBarButton");
if (mode == "hide")
{
(document.getElementById("sidebar")).setAttribute("toggle","hide");
setStylesheet(this.settings.styleHide,"ToggleSideBarStyles");
}
};
config.macros.toggleSideBar.onToggleSideBar = function(){
var sidebar = document.getElementById("sidebar");
var settings = config.macros.toggleSideBar.settings;
if (sidebar.getAttribute("toggle")=='hide')
{
setStylesheet(settings.styleShow,"ToggleSideBarStyles");
sidebar.setAttribute("toggle","show");
this.firstChild.data= (this.firstChild.data).replace(settings.arrow1,settings.arrow2);
}
else
{
setStylesheet(settings.styleHide,"ToggleSideBarStyles");
sidebar.setAttribute("toggle","hide");
this.firstChild.data= (this.firstChild.data).replace(settings.arrow2,settings.arrow1);
}
return false;
}
setStylesheet(".HideSideBarButton .button {font-weight:bold; padding: 0 5px;}\n","ToggleSideBarButtonStyles");
//}}}
<<formTiddler NewPluginTemplate>><data>{"twversion":"2.1","category":"Toggling page elements","format":"Script","link":"http://www.tiddlytools.com","author":"Eric Shulman (~TiddlyTools)","description":"show/hide document 'header' area (containing SiteTitle and SiteSubtitle content)"}</data>
Type the text for 'ToggleTagMacro'
/***
|Name:|ToggleTagPlugin|
|Description:|Makes a checkbox which toggles a tag in a tiddler|
|Version:|3.1.0 ($Rev: 4331 $)|
|Date:|$Date: 2008-04-12 13:42:50 +1000 (Sat, 12 Apr 2008) $|
|Source:|http://mptw.tiddlyspot.com/#ToggleTagPlugin|
|Author:|Simon Baird <simon.baird@gmail.com>|
|License:|http://mptw.tiddlyspot.com/#TheBSDLicense|
!!Usage
{{{<<toggleTag }}}//{{{TagName TiddlerName LabelText}}}//{{{>>}}}
* TagName - the tag to be toggled, default value "checked"
* TiddlerName - the tiddler to toggle the tag in, default value the current tiddler
* LabelText - the text (gets wikified) to put next to the check box, default value is '{{{[[TagName]]}}}' or '{{{[[TagName]] [[TiddlerName]]}}}'
(If a parameter is '.' then the default will be used)
* TouchMod flag - if non empty then touch the tiddlers mod date. Note, can set config.toggleTagAlwaysTouchModDate to always touch mod date
!!Examples
|Code|Description|Example|h
|{{{<<toggleTag>>}}}|Toggles the default tag (checked) in this tiddler|<<toggleTag>>|
|{{{<<toggleTag TagName>>}}}|Toggles the TagName tag in this tiddler|<<toggleTag TagName>>|
|{{{<<toggleTag TagName TiddlerName>>}}}|Toggles the TagName tag in the TiddlerName tiddler|<<toggleTag TagName TiddlerName>>|
|{{{<<toggleTag TagName TiddlerName 'click me'>>}}}|Same but with custom label|<<toggleTag TagName TiddlerName 'click me'>>|
|{{{<<toggleTag . . 'click me'>>}}}|dot means use default value|<<toggleTag . . 'click me'>>|
!!Notes
* If TiddlerName doesn't exist it will be silently created
* Set label to '-' to specify no label
* See also http://mgtd-alpha.tiddlyspot.com/#ToggleTag2
!!Known issues
* Doesn't smoothly handle the case where you toggle a tag in a tiddler that is current open for editing
* Should convert to use named params
***/
//{{{
if (config.toggleTagAlwaysTouchModDate == undefined) config.toggleTagAlwaysTouchModDate = false;
merge(config.macros,{
toggleTag: {
createIfRequired: true,
shortLabel: "[[%0]]",
longLabel: "[[%0]] [[%1]]",
handler: function(place,macroName,params,wikifier,paramString,tiddler) {
var tag = (params[0] && params[0] != '.') ? params[0] : "checked";
var title = (params[1] && params[1] != '.') ? params[1] : tiddler.title;
var defaultLabel = (title == tiddler.title ? this.shortLabel : this.longLabel);
var label = (params[2] && params[2] != '.') ? params[2] : defaultLabel;
var touchMod = (params[3] && params[3] != '.') ? params[3] : "";
label = (label == '-' ? '' : label); // dash means no label
var theTiddler = (title == tiddler.title ? tiddler : store.getTiddler(title));
var cb = createTiddlyCheckbox(place, label.format([tag,title]), theTiddler && theTiddler.isTagged(tag), function(e) {
if (!store.tiddlerExists(title)) {
if (config.macros.toggleTag.createIfRequired) {
var content = store.getTiddlerText(title); // just in case it's a shadow
store.saveTiddler(title,title,content?content:"",config.options.txtUserName,new Date(),null);
}
else
return false;
}
if ((touchMod != "" || config.toggleTagAlwaysTouchModDate) && theTiddler)
theTiddler.modified = new Date();
store.setTiddlerTag(title,this.checked,tag);
return true;
});
}
}
});
//}}}
<<forEachTiddler
where
'tiddler.tags.contains("list") && tiddler.data("category") == "Toggling page elements"'
sortBy
'tiddler.title'
write
'"|vertical-align:top;@@white-space: nowrap;{{large{[["
+tiddler.title
+"]]}}}@@<br>{{bold{Format:}}} "
+tiddler.data("format")
+"<br>{{bold{Author:}}} "
+tiddler.data("author")
+"<br>{{bold{Link:}}} "
+"[[here|"
+tiddler.data("link")
+"]] <br>{{bold{For TW version:}}} "
+tiddler.data("twversion")
+"|vertical-align:top;{{bold{Description:}}}<br>"
+tiddler.data("description")
+"|\n"'
>>
<!--{{{-->
<!-- div class='toolbar' macro='toolbar closeTiddler closeOthers +editTiddler > fields syncing permalink references jump'></div-->
<div macro="showWhen readOnly"><!-- cut-down toolbar for web users -->
<div class='toolbar' macro='toolbar fullscreen permalink'></div>
</div>
<div macro="hideWhen readOnly"><!-- regular toolbar for me -->
<div class='toolbar' macro='toolbar closeTiddler closeOthers +editTiddler > fields syncing permalink references jump'></div>
</div>
<div class='title' macro='view title'></div>
<div class='subtitle'><span macro='view modifier link'></span>, <span macro='view modified date'></span> (<span macro='message views.wikified.createdPrompt'></span> <span macro='view created date'></span>)</div>
<div class='tagging' macro='tagging'></div>
<!-- div class='tagged' macro='tags'></div -->
<div class='viewer' macro='view text wikified'></div>
<div class='tagClear'></div>
<!--}}}-->
Per vedere correttamente le formule presenti in queste pagine si deve utilizzare un browser che legga il codice MathML, ad esempio Firefox. To view correctly the math dispayed in these pages you need a MathML-enabled browser, for instance Firefox. Prodotte con [[TiddlyWiki|http://www.tiddlywiki.com]] © Osmosoft
//{{{
//This ensures that the footer sticks to the bottom of the screen when there are no tiddlers open. If that is not desirable, it can be deleted.
function setFooter() {
if (document.getElementById && document.getElementById("contentFooter") ) {
var windowHeight=findWindowHeight();
if (windowHeight>0) {
var contentHeight= document.getElementById('mainMenu').offsetHeight + document.getElementById("header").offsetHeight + document.getElementById("contentFooter").offsetHeight;
var menu= document.getElementById('mainMenu');
if (windowHeight-(contentHeight)>=0) {
menu.style.position='relative';
menu.style.marginBottom=(windowHeight-(contentHeight))+'px';
}
else {
menu.style.position='';
menu.style.marginBottom='';
}
}
}
}
window.onresize = function() {
setFooter();
}
Story.prototype.refreshTiddler_footerhack=Story.prototype.refreshTiddler;
Story.prototype.refreshTiddler = function (title,template,force)
{
var theTiddler = Story.prototype.refreshTiddler_footerhack.apply(this,arguments);
setFooter();
return theTiddler;}
//}}}