Welcome to TiddlyWiki created by Jeremy Ruston, Copyright © 2007 UnaMesa Association
Este material foi baseado nas notas de aula dos Profs. Carlos Henrique C. Ribeiro e Celso Renna.
/***
|Name|AliasPlugin|
|Source|http://www.TiddlyTools.com/#AliasPlugin|
|Documentation|http://www.TiddlyTools.com/#AliasPluginInfo|
|Version|1.1.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|Create text-substitution macros|
Define macros for abbreviations and other "aliases", and then embed them in the rest of your tiddler content to quickly insert common terms, phrases and links without a lot of repetitive typing.
!!!!!Documentation
> see [[AliasPluginInfo]]
!!!!!Revisions
<<<
2008.03.11 [*.*.*] plugin size reduction - documentation moved to [[AliasPluginInfo]]
2007.03.21 [1.1.0] added support for parameter substitution into alias macros, using format() method and%0..%9 markers
| Please see [[AliasPluginInfo]] for previous revision details |
2005.08.12 [1.0.0] initial release
<<<
!!!!!Code
***/
//{{{
version.extensions.alias= {major: 1, minor: 1, revision: 0, date: new Date(2007,3,21)};
config.macros.alias= { };
config.macros.alias.handler = function(place,macroName,params) {
var alias=params.shift(); if (!alias) return; alias=alias.replace(/ /g,"_"); // don't allow spaces in alias
if (config.macros[alias]==undefined) // create new macro (as needed)
{
config.macros[alias] = { };
config.macros[alias].handler =
function (place,macroName,params)
{ wikify(config.macros[macroName].text.format(params),place,null,null); }
}
config.macros[alias].text = params[0]?params.join(' '):alias; // set alias text
}
//}}}
/***
|Name|AliasPlugin|
|Source|http://www.TiddlyTools.com/#AliasPlugin|
|Documentation|http://www.TiddlyTools.com/#AliasPluginInfo|
|Version|1.1.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|documentation|
|Requires||
|Overrides||
|Description|documentation for AliasPlugin|
Define macros for abbreviations and other "aliases", and then embed them in the rest of your tiddler content to quickly insert common terms, phrases and links without a lot of repetitive typing.
!!!!!Usage
<<<
First, decide upon a suitable "alias" for the text to be substituted. This is usually a short keyword or other abbreviated term that is easily input with just a few keystrokes. You can use any alias you like, but don't include any spaces in the alias name, since it will be used as the name of the 'alias macro' that is created, and macro names cannot contain spaces.
//Note: If you use an alias name that ''does'' contain spaces, they will be automatically replaced with underscores ("_"), so that the resulting alias name will still be a valid macro name//
To create alias definitions, embed {{{<<alias newname "text to display"}}} >> macros in a tiddler. These macros don't actually produce any visible output, but simply define the alias macros that you want to use in your document, and thus they can be safely added to practically any tiddler without producing a change in that tiddler's appearance.
//Note: In order to ensure that your aliases are defined and available for use throughout your document, you should add your definitions to a tiddler that you are certain will be displayed when your TW is first loaded, such as //[[MainMenu]]// or //[[SiteTitle]]// (or, any tiddler listed in //[[DefaultTiddlers]]//).//
Then, you can use the aliases you have defined like this: {{{<<newname>>}}}. You can include additional parameters when you invoke the macro: {{{<<newname param param param...>>}}}. These parameters are inserted into the macro's "text to display" by substituting for %0...%9 markers.
For example, to define a quick alias for inserting a link to any given subject on www.wikipedia.com, you can write:
{{{
<<alias wikipedia "[[Wikipedia:%0|http://www.wikipedia.com/wiki/%0]]">>
}}}
which allows you to then write:
{{{
<<wikipedia TiddlyWiki>>
}}}
which is processed as if you wrote:
{{{
[[Wikipedia:TiddlyWiki|http://www.wikipedia.com/wiki/TiddlyWiki]]
}}}
and is displayed this way:
><<alias wikipedia "[[Wikipedia:%0|http://www.wikipedia.com/wiki/%0]]">><<wikipedia TiddlyWiki>>
Another interesting example uses the substitution markers to automatically display a reference to a TiddlerSlice value:
{{{
<<alias describe {{"\<\<tiddler [[%0::Description]]\>\>"}}>>
}}}
which allows you to then write:
{{{
<<describe AliasPlugin>>
}}}
which is processed as if you wrote:
{{{
<<tiddler [[AliasPlugin::Description]]>>
}}}
and is displayed this way:
><<alias describe {{"\<\<tiddler [[%0::Description]]\>\>"}}>><<describe AliasPlugin>>
<<<
!!!!!Examples
<<<
<<alias>> {{{<<alias>>}}}
missing alias name: fail safe, do nothing
<<alias alias1>> {{{<<alias alias1>>}}}
missing text params, default to text=name (e.g., "<<alias1>>")
<<alias alias2 simple multi-word text substitution>> {{{<<alias alias2 simple multi-word text substitution>>}}}
<<alias2>>
<<alias "alias3 with spaces" "spaces in aliasname converted to _">> {{{<<alias "alias3 with spaces" "spaces in aliasname converted to _ ">>}}}
<<alias3_with_spaces>>
<<alias alias4 "multi-line
text
substitution">> {{{<<alias alias4 "multi-line
text
substitution">>}}}
<<alias4>>
<<<
!!!!!Revisions
<<<
2008.03.11 [*.*.*] plugin size reduction - documentation moved to [[AliasPluginInfo]]
2007.03.21 [1.1.0] added support for parameter substitution into alias macros, using format() method and%0..%9 markers
2005.10.09 [1.0.3] combined documentation and code into a single tiddler
2005.08.12 [1.0.0] initial release
<<<
text/plain
.txt .text .js .vbs .asp .cgi .pl
----
text/html
.htm .html .hta .htx .mht
----
text/comma-separated-values
.csv
----
text/javascript
.js
----
text/css
.css
----
text/xml
.xml .xsl .xslt
----
image/gif
.gif
----
image/jpeg
.jpg .jpe .jpeg
----
image/png
.png
----
image/bmp
.bmp
----
image/tiff
.tif .tiff
----
audio/basic
.au .snd
----
audio/wav
.wav
----
audio/x-pn-realaudio
.ra .rm .ram
----
audio/x-midi
.mid .midi
----
audio/mp3
.mp3
----
audio/m3u
.m3u
----
video/x-ms-asf
.asf
----
video/avi
.avi
----
video/mpeg
.mpg .mpeg
----
video/quicktime
.qt .mov .qtvr
----
application/pdf
.pdf
----
application/rtf
.rtf
----
application/postscript
.ai .eps .ps
----
application/wordperfect
.wpd
----
application/mswrite
.wri
----
application/msexcel
.xls .xls3 .xls4 .xls5 .xlw
----
application/msword
.doc
----
application/mspowerpoint
.ppt .pps
----
application/x-director
.swa
----
application/x-shockwave-flash
.swf
----
application/x-zip-compressed
.zip
----
application/x-gzip
.gz
----
application/x-rar-compressed
.rar
----
application/octet-stream
.com .exe .dll .ocx
----
application/java-archive
.jar
[[AttachFilePlugin]] reads binary data from locally-stored files (e.g., images, PDFs, mp3's, etc.) and converts it to base64-encoded text that is stored in tiddlers tagged with<<tag attachment>>. [[AttachFilePluginFormatters]] allows you to use those tiddlers in place of the external path/file references that are normally part of the image and external links wiki syntax.
[[FileDropPlugin]] and [[FileDropPluginConfig]] allow you to quickly create attachment tiddlers simply by dragging files directly from your system's desktop folder display and dropping it onto an open TiddlyWiki document. Text files are automatically created as simple tiddlers, while binary files are automatically encoded and attached.
/***
|Name|AttachFilePlugin|
|Source|http://www.TiddlyTools.com/#AttachFilePlugin|
|Documentation|http://www.TiddlyTools.com/#AttachFilePluginInfo|
|Version|3.8.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|AttachFilePluginFormatters, AttachFileMIMETypes|
|Overrides||
|Description|Store binary files as base64-encoded tiddlers with fallback links for separate local and/or remote file storage|
Store or link binary files (such as jpg, gif, pdf or even mp3) within your TiddlyWiki document and then use them as images or links from within your tiddler content.
> Important note: As of version 3.6.0, in order to //render// images and other binary attachments created with this plugin, you must also install [[AttachFilePluginFormatters]], which extends the behavior of the TiddlyWiki core formatters for embedded images ({{{[img[tooltip|image]]}}}), linked embedded images ({{{[img[tooltip|image][link]]}}}), and external/"pretty" links ({{{[[label|link]]}}}), so that these formatter will process references to attachment tiddlers as if a normal file reference had been provided. |
!!!!!Documentation
>see [[AttachFilePluginInfo]]
!!!!!Inline interface (live)
>see [[AttachFile]] (shadow tiddler)
><<tiddler AttachFile>>
!!!!!Revisions
<<<
2008.05.12 [3.8.1] automatically add 'attach' task to backstage (moved from BackstageTweaks)
2008.04.09 [3.8.0] in onChangeSource(), if source matches current document folder, use relative reference for local link. Also, disable 'embed' when using IE (which //still// doesn't support data: URI)
2008.04.07 [3.7.3] fixed typo in HTML for 'local file link' so that clicking in input field doesn't erase current path/file (if any)
2008.04.07 [3.7.2] auto-create AttachFile shadow tiddler for inline interface
2008.01.08 [*.*.*] plugin size reduction: documentation moved to ...Info
2007.12.04 [*.*.*] update for TW2.3.0: replaced deprecated core functions, regexps, and macros
2007.12.03 [3.7.1] in createAttachmentTiddler(), added optional "noshow" flag to suppress display of newly created tiddlers.
|please see [[AttachFilePluginInfo]] for additional revision details|
2005.07.20 [1.0.0] Initial Release
<<<
!!!!!Code
***/
// // version
//{{{
version.extensions.attach = {major: 3, minor: 8, revision: 1, date: new Date(2008,5,12)};
// shadow tiddler
config.shadowTiddlers.AttachFile="<<attach inline>>";
// add 'attach' backstage task (insert before built-in 'importTask')
if (config.tasks) { // for TW2.2b or above
config.tasks.attachTask = {
text: "attach",
tooltip: "Attach a binary file as a tiddler",
content: "<<attach inline>>"
}
config.backstageTasks.splice(config.backstageTasks.indexOf("importTask"),0,"attachTask");
}
config.macros.attach = {
// // lingo
//{{{
label: "attach file",
tooltip: "Attach a file to this document",
linkTooltip: "Attachment: ",
typeList: "AttachFileMIMETypes",
titlePrompt: " enter tiddler title...",
MIMEPrompt: "<option value=''>select MIME type...</option><option value='editlist'>[edit list...]</option>",
localPrompt: " enter local path/filename...",
URLPrompt: " enter remote URL...",
tiddlerErr: "Please enter a tiddler title",
sourceErr: "Please enter a source path/filename",
storageErr: "Please select a storage method: embedded, local or remote",
MIMEErr: "Unrecognized file format. Please select a MIME type",
localErr: "Please enter a local path/filename",
URLErr: "Please enter a remote URL",
fileErr: "Invalid path/file or file not found",
sourceReport: "| source file:|{{{%0}}}|\n",
nosourceReport: "| source file:|//none//|\n",
dateReport: "| attached on:|%0 by %1|\n",
notesReport: "| description:|%0|\n",
dataReport: "| embedded:|[[%0|%0]] - {{{type=%1, size=%2 bytes, encoded=%3 bytes}}}|\n",
nodataReport: "| embedded:|//none//|\n",
localReport: "| local file:|/%LOCAL_LINK%/[[%0|%1]]|\n",
nolocalReport: "| local file:|//none//|\n",
URLReport: "| remote link:|/%REMOTE_LINK%/[[%0|%0]]|\n",
noURLReport: "| remote link:|//none//|\n",
imageReport: "image\n<<<\nusage: {{{[img[tooltip|%0]] or [img[tooltip|%0][link]]}}}\n[img[tooltip|%0]]\n<<<\n",
dataBlock: "\n/% DO NOT EDIT BELOW THIS POINT\n---BEGIN_DATA---\n%0;base64,\n%1\n---END_DATA---\n%/",
//}}}
// // macro definition
//{{{
handler:
function(place,macroName,params) {
if (params && !params[0]) { createTiddlyButton(place,this.label,this.tooltip,this.toggleAttachPanel); return; }
var id=params.shift();
this.createAttachPanel(place,id+"_attachPanel",params);
document.getElementById(id+"_attachPanel").style.position="static";
document.getElementById(id+"_attachPanel").style.display="block";
},
//}}}
//{{{
createAttachPanel:
function(place,panel_id,params) {
if (!panel_id || !panel_id.length) var panel_id="_attachPanel";
// remove existing panel (if any)
var panel=document.getElementById(panel_id); if (panel) panel.parentNode.removeChild(panel);
// set styles for this panel
setStylesheet(this.css,"attachPanel");
// create new panel
var title=""; if (params && params[0]) title=params.shift();
var types=this.MIMEPrompt+this.formatListOptions(store.getTiddlerText(this.typeList)); // get MIME types
panel=createTiddlyElement(place,"span",panel_id,"attachPanel",null);
var html=this.html.replace(/%id%/g,panel_id);
html=html.replace(/%title%/g,title);
html=html.replace(/%disabled%/g,title.length?"disabled":"");
html=html.replace(/%IEdisabled%/g,config.browser.isIE?"disabled":"");
html=html.replace(/%types%/g,types);
panel.innerHTML=html;
return panel;
},
//}}}
//{{{
toggleAttachPanel:
function (e) {
if (!e) var e = window.event;
var parent=resolveTarget(e).parentNode;
var panel = document.getElementById("_attachPanel");
if (panel==undefined || panel.parentNode!=parent)
panel=config.macros.attach.createAttachPanel(parent,"_attachPanel");
var isOpen = panel.style.display=="block";
if(config.options.chkAnimate)
anim.startAnimating(new Slider(panel,!isOpen,e.shiftKey || e.altKey,"none"));
else
panel.style.display = isOpen ? "none" : "block" ;
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
return(false);
},
//}}}
//{{{
formatListOptions:
function(text) {
if (!text || !text.trim().length) return "";
// get MIME list content from text
var parts=text.split("\n----\n");
var out="";
for (var p=0; p<parts.length; p++) {
var lines=parts[p].split("\n");
var label=lines.shift(); // 1st line=display text
var value=lines.shift(); // 2nd line=item value
out +='<option value="%1">%0</option>'.format([label,value]);
}
return out;
},
//}}}
// // interface definition
//{{{
css:
".attachPanel { display: none; position:absolute; z-index:10; width:35em; right:105%; top:0em;\
background-color: #eee; color:#000; font-size: 8pt; line-height:110%;\
border:1px solid black; border-bottom-width: 3px; border-right-width: 3px;\
padding: 0.5em; margin:0em; -moz-border-radius:1em; text-align:left }\
.attachPanel form { display:inline;border:0;padding:0;margin:0; }\
.attachPanel select { width:99%;margin:0px;font-size:8pt;line-height:110%;}\
.attachPanel input { width:98%;padding:0px;margin:0px;font-size:8pt;line-height:110%}\
.attachPanel textarea { width:98%;margin:0px;height:2em;font-size:8pt;line-height:110%}\
.attachPanel table { width:100%;border:0;margin:0;padding:0;color:inherit; }\
.attachPanel tbody, .attachPanel tr, .attachPanel td { border:0;margin:0;padding:0;color:#000; }\
.attachPanel .box { border:1px solid black; padding:.3em; margin:.3em 0px; background:#f8f8f8; -moz-border-radius:5px; }\
.attachPanel .chk { width:auto;border:0; }\
.attachPanel .btn { width:auto; }\
.attachPanel .btn2 { width:49%; }\
",
//}}}
//{{{
html:
'<form>\
attach from source file <input type="file" name="source" size=56 onChange="config.macros.attach.onChangeSource(this)">\
<div class="box">\
<table style="border:0"><tr style="border:0"><td style="border:0;text-align:right;width:1%;white-space:nowrap">\
embed data <input type=checkbox class=chk name="useData" %IEdisabled% \
onclick="if (!this.form.MIMEType.value.length)\
this.form.MIMEType.selectedIndex=this.checked?1:0; "> \
</td><td style="border:0">\
<select size=1 name="MIMEType" \
onchange="this.title=this.value; if (this.value==\'editlist\')\
{ this.selectedIndex=this.form.useData.checked?1:0; story.displayTiddler(null,config.macros.attach.typeList,2); return; }">\
<option value=""></option>\
%types%\
</select>\
</td></tr><tr style="border:0"><td style="border:0;text-align:right;width:1%;white-space:nowrap">\
local link <input type=checkbox class=chk name="useLocal"\
onclick="this.form.local.value=this.form.local.defaultValue=this.checked?config.macros.attach.localPrompt:\'\';"> \
</td><td style="border:0">\
<input type=text name="local" size=15 autocomplete=off value=""\
onchange="this.form.useLocal.checked=this.value.length" \
onkeyup="this.form.useLocal.checked=this.value.length" \
onfocus="if (!this.value.length) this.value=config.macros.attach.localPrompt; this.select()">\
</td></tr><tr style="border:0"><td style="border:0;text-align:right;width:1%;white-space:nowrap">\
remote link <input type=checkbox class=chk name="useURL"\
onclick="this.form.URL.value=this.form.URL.defaultValue=this.checked?config.macros.attach.URLPrompt:\'\';\"> \
</td><td style="border:0">\
<input type=text name="URL" size=15 autocomplete=off value=""\
onfocus="if (!this.value.length) this.value=config.macros.attach.URLPrompt; this.select()"\
onchange="this.form.useURL.checked=this.value.length;"\
onkeyup="this.form.useURL.checked=this.value.length;">\
</td></tr></table>\
</div>\
<table style="border:0"><tr style="border:0"><td style="border:0;text-align:right;width:1%;white-space:nowrap">\
attach as \
</td><td style="border:0" colspan=2>\
<input type=text name="tiddlertitle" size=15 autocomplete=off value="%title%"\
onkeyup="if (!this.value.length) { this.value=config.macros.attach.titlePrompt; this.select(); }"\
onfocus="if (!this.value.length) this.value=config.macros.attach.titlePrompt; this.select()" %disabled%>\
</td></tr><tr style="border:0"><td style="border:0;text-align:right;width:1%;white-space:nowrap">\
description \
</td><td style="border:0" colspan=2>\
<input type=text name="notes" size=15 autocomplete=off>\
</td></tr><tr style="border:0"><td style="border:0;text-align:right;width:1%;white-space:nowrap">\
add tags \
</td><td style="border:0">\
<input type=text name="tags" size=15 autocomplete=off value="" onfocus="this.select()">\
</td><td style="width:40%;text-align:right;border:0">\
<input type=button class=btn2 value="attach"\
onclick="config.macros.attach.onClickAttach(this)"><!--\
--><input type=button class=btn2 value="close"\
onclick="var panel=document.getElementById(\'%id%\'); if (panel) panel.parentNode.removeChild(panel);">\
</td></tr></table>\
</form>',
//}}}
// // control processing
//{{{
onChangeSource:
function(here) {
var form=here.form;
var list=form.MIMEType;
var theFilename = form.source.value;
var theExtension = theFilename.substr(theFilename.lastIndexOf('.')).toLowerCase();
// if theFilename is in current document folder, remove path prefix and use relative reference
var h=document.location.href; folder=getLocalPath(decodeURIComponent(h.substr(0,h.lastIndexOf("/")+1)));
if (theFilename.substr(0,folder.length)==folder) theFilename='./'+theFilename.substr(folder.length);
else theFilename='file:///'+theFilename; // otherwise, use absolute reference
theFilename=theFilename.replace(/\\/g,"/"); // fixup: change \ to /
form.useLocal.checked = true;
form.local.value = theFilename;
form.useData.checked = !form.useData.disabled;
list.selectedIndex=1;
for (var i=0; i<list.options.length; i++) // find matching MIME type
if (list.options[i].value.indexOf(theExtension)!=-1) { list.selectedIndex = i; break; }
if (!form.tiddlertitle.disabled)
form.tiddlertitle.value=theFilename.substr(theFilename.lastIndexOf('/')+1); // get tiddlername from filename
},
//}}}
//{{{
onClickAttach:
function (here) {
clearMessage();
// get input values
var form=here.form;
var theDate=(new Date()).formatString(config.macros.timeline.dateFormat);
var theSource = form.source.value!=form.source.defaultValue?form.source.value:"";
var theTitle=form.tiddlertitle.value;
var theLocal = form.local.value!=form.local.defaultValue?form.local.value:"";
var theURL = form.URL.value!=form.URL.defaultValue?form.URL.value:"";
var theNotes = form.notes.value;
var theTags = "attachment excludeMissing "+form.tags.value;
var useData=form.useData.checked;
var useLocal=form.useLocal.checked;
var useURL=form.useURL.checked;
var theMIMEType = form.MIMEType.value.length?form.MIMEType.options[form.MIMEType.selectedIndex].text:"";
// validate checkboxes and get filename
if (useData) {
if (theSource.length) { if (!theLocation) var theLocation=theSource; }
else { alert(this.sourceErr); form.source.focus(); return false; }
}
if (useLocal) {
if (theLocal.length) { if (!theLocation) var theLocation = theLocal; }
else { alert(this.localErr); form.local.focus(); return false; }
}
if (useURL) {
if (theURL.length) { if (!theLocation) var theLocation = theURL; }
else { alert(this.URLErr); form.URL.focus(); return false; }
}
if (!(useData||useLocal||useURL))
{ form.useData.focus(); alert(this.storageErr); return false; }
if (!theLocation)
{ form.source.focus(); alert(this.sourceErr); return false; }
if (!theTitle || !theTitle.trim().length || theTitle==this.titlePrompt)
{ form.tiddlertitle.focus(); alert(this.tiddlerErr); return false; }
// if not already selected, determine MIME type based on filename extension (if any)
if (useData && !theMIMEType.length && theLocation.lastIndexOf('.')!=-1) {
var theExt = theLocation.substr(theLocation.lastIndexOf('.')).toLowerCase();
var theList=form.MIMEType;
for (var i=0; i<theList.options.length; i++)
if (theList.options[i].value.indexOf(theExt)!=-1)
{ var theMIMEType=theList.options[i].text; theList.selectedIndex=i; break; }
}
// attach the file
return this.createAttachmentTiddler(theSource, theDate, theNotes, theTags, theTitle,
useData, useLocal, useURL, theLocal, theURL, theMIMEType);
},
getMIMEType:
function(src,def) {
var ext = src.substr(src.lastIndexOf('.')).toLowerCase();
var list=store.getTiddlerText(this.typeList);
if (!list || !list.trim().length) return def;
// get MIME list content from tiddler
var parts=list.split("\n----\n");
for (var p=0; p<parts.length; p++) {
var lines=parts[p].split("\n");
var mime=lines.shift(); // 1st line=MIME type
var match=lines.shift(); // 2nd line=matching extensions
if (match.indexOf(ext)!=-1) return mime;
}
return def;
},
createAttachmentTiddler:
function (theSource, theDate, theNotes, theTags, theTitle,
useData, useLocal, useURL, theLocal, theURL, theMIMEType, noshow) {
// encode the data
if (useData) {
if (!theMIMEType.length) {
alert(this.MIMEErr);
form.MIMEType.selectedIndex=1; form.MIMEType.focus();
return false;
}
var theData = this.readFile(theSource); if (!theData) { return false; }
displayMessage('encoding '+theSource);
var theEncoded = this.encodeBase64(theData);
displayMessage('file size='+theData.length+' bytes, encoded size='+theEncoded.length+' bytes');
}
// generate tiddler and refresh
var theText = "";
theText +=theSource.length?this.sourceReport.format([theSource]):this.nosourceReport;
theText +=this.dateReport.format([theDate,config.options.txtUserName]);
theText +=theNotes.length?this.notesReport.format([theNotes]):"";
theText +=useData?this.dataReport.format([theTitle,theMIMEType,theData.length,theEncoded.length]):this.nodataReport;
theText +=useLocal?this.localReport.format([theLocal,theLocal.replace(/\\/g,"/")]):this.nolocalReport;
theText +=useURL?this.URLReport.format([theURL]):this.noURLReport;
theText +=(theMIMEType.substr(0,5)=="image")?this.imageReport.format([theTitle]):"";
theText +=useData?this.dataBlock.format([theMIMEType,theEncoded]):"";
store.saveTiddler(theTitle,theTitle,theText,config.options.txtUserName,new Date(),theTags);
var panel=document.getElementById("attachPanel"); if (panel) panel.style.display="none";
if (!noshow) { story.displayTiddler(null,theTitle); story.refreshTiddler(theTitle,null,true); }
displayMessage('attached "'+theTitle+'"');
return true;
},
//}}}
// // base64 conversion
//{{{
encodeBase64:
function (theData) {
if (!theData) return null;
// encode as base64
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var out = ""; //This is the output
var chr1, chr2, chr3 = ""; //These are the 3 bytes to be encoded
var enc1, enc2, enc3, enc4 = ""; //These are the 4 encoded bytes
for (var count=0,i=0; i<theData.length; )
{
chr1 = theData.charCodeAt(i++); //Grab the first byte
chr2 = theData.charCodeAt(i++); //Grab the second byte
chr3 = theData.charCodeAt(i++); //Grab the third byte
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2))
enc3 = enc4 = 64;
else if (isNaN(chr3))
enc4 = 64;
out += keyStr.charAt(enc1)+keyStr.charAt(enc2)+keyStr.charAt(enc3)+keyStr.charAt(enc4);
chr1 = chr2 = chr3 = "";
enc1 = enc2 = enc3 = enc4 = "";
count+=4; if (count>60) { out+='\n'; count=0; } // add line break every 60 chars for readability
}
return out;
},
//}}}
// // I/O functions
//{{{
readFile: // read local BINARY file data
function(filePath) {
if(!window.Components) { return null; }
try { netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); }
catch(e) { alert("access denied: "+filePath); return null; }
var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
try { file.initWithPath(filePath); } catch(e) { alert("cannot read file - invalid path: "+filePath); return null; }
if (!file.exists()) { alert("cannot read file - not found: "+filePath); return null; }
var inputStream = Components.classes["@mozilla.org/network/file-input-stream;1"].createInstance(Components.interfaces.nsIFileInputStream);
inputStream.init(file, 0x01, 00004, null);
var bInputStream = Components.classes["@mozilla.org/binaryinputstream;1"].createInstance(Components.interfaces.nsIBinaryInputStream);
bInputStream.setInputStream(inputStream);
return(bInputStream.readBytes(inputStream.available()));
},
//}}}
//{{{
writeFile:
function(filepath,data) {
// TBD: decode base64 and write BINARY data to specified local path/filename
return(false);
}
};
//}}}
/***
|Name|AttachFilePluginFormatters|
|Source|http://www.TiddlyTools.com/#AttachFilePluginFormatters|
|Version|3.7.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|'image' and 'prettyLink' formatters, TiddlyWiki.prototype.getRecursiveTiddlerText|
|Description|run-time library for displaying attachment tiddlers|
This plugin provides "stand-alone" processing for //rendering// attachment tiddlers created by [[AttachFilePlugin]]. Attachment tiddlers are tagged with<<tag attachment>>and contain binary file content (e.g., jpg, gif, pdf, mp3, etc.) that has been stored directly as base64 text-encoded data or can be loaded from external files stored on a local filesystem or remote web server.
NOTE: This plugin does not include the "control panel" and supporting functions needed to //create// new attachment tiddlers. Those features are provided by [[AttachFilePlugin]], which can be installed while building your document, and then safely omitted to reduce the overall file size when you publish your finished document (assuming you don't intend to create any additional attachment tiddlers in that document)
!!!!!Formatters
<<<
This plugin extends the behavior of the following TiddlyWiki core "wikify()" formatters:
* embedded images: {{{[img[tooltip|image]]}}}
* linked embedded images: {{{[img[tooltip|image][link]]}}}
* external/"pretty" links: {{{[[label|link]]}}}
''Please refer to AttachFilePlugin (source: http://www.TiddlyTools.com/#AttachFilePlugin) for additional information.''
<<<
!!!!!Revisions
<<<
2007.12.04 [*.*.*] update for TW2.3.0: replaced deprecated core functions, regexps, and macros
2007.10.29 [3.7.0] more code reduction: removed upload handling from AttachFilePlugin (saves ~7K!)
2007.10.28 [3.6.0] removed duplicate formatter code from AttachFilePlugin (saves ~10K!) and updated documentation accordingly. This plugin ([[AttachFilePluginFormatters]]) is now //''required''// in order to display attached images/binary files within tiddler content.
2006.05.20 [3.4.0] through 2007.03.01 [3.5.3] sync with AttachFilePlugin
2006.05.13 [3.2.0] created from AttachFilePlugin v3.2.0
<<<
!!!!!Code
***/
// // version
//{{{
version.extensions.attach = {major: 3, minor: 7, revision: 0, date: new Date(2007,10,28)};
//}}}
//{{{
if (config.macros.attach==undefined) config.macros.attach= { };
//}}}
//{{{
if (config.macros.attach.isAttachment==undefined) config.macros.attach.isAttachment=function (title) {
var tiddler = store.getTiddler(title);
if (tiddler==undefined || tiddler.tags==undefined) return false;
return (tiddler.tags.indexOf("attachment")!=-1);
}
//}}}
//{{{
// test for local file existence
// Returns true/false without visible error display
// Uses Components for FF and ActiveX FSO object for MSIE
if (config.macros.attach.fileExists==undefined) config.macros.attach.fileExists=function(theFile) {
var found=false;
// DEBUG: alert('testing fileExists('+theFile+')...');
if(window.Components) {
try { netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); }
catch(e) { return false; } // security access denied
var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
try { file.initWithPath(theFile); }
catch(e) { return false; } // invalid directory
found = file.exists();
}
else { // use ActiveX FSO object for MSIE
var fso = new ActiveXObject("Scripting.FileSystemObject");
found = fso.FileExists(theFile)
}
// DEBUG: alert(theFile+" "+(found?"exists":"not found"));
return found;
}
//}}}
//{{{
if (config.macros.attach.getAttachment==undefined) config.macros.attach.getAttachment=function(title) {
// extract embedded data, local and remote links (if any)
var startmarker="---BEGIN_DATA---\n";
var endmarker="\n---END_DATA---";
var pos=0; var endpos=0;
var text = store.getTiddlerText(title);
var embedded="";
var locallink="";
var remotelink="";
// look for embedded data, convert to data: URI
if ((pos=text.indexOf(startmarker))!=-1 && (endpos=text.indexOf(endmarker))!=-1)
embedded="data:"+(text.substring(pos+startmarker.length,endpos)).replace(/\n/g,'');
if (embedded.length && !config.browser.isIE)
return embedded; // use embedded data if any... except for IE, which doesn't support data URI
// no embedded data... fallback to local/remote reference links...
// look for 'attachment link markers'
if ((pos=text.indexOf("/%LOCAL_LINK%/"))!=-1)
locallink=text.substring(text.indexOf("|",pos)+1,text.indexOf("]]",pos));
if ((pos=text.indexOf("/%REMOTE_LINK%/"))!=-1)
remotelink=text.substring(text.indexOf("|",pos)+1,text.indexOf("]]",pos));
// document is being served remotely... use remote URL (if any) (avoids security alert)
if (remotelink.length && document.location.protocol!="file:")
return remotelink;
// local link only... return link without checking file existence (avoids security alert)
if (locallink.length && !remotelink.length)
return locallink;
// local link, check for file exist... use local link if found
if (locallink.length) {
if (this.fileExists(getLocalPath(locallink))) return locallink;
// maybe local link is relative... add path from current document and try again
var pathPrefix=document.location.href; // get current document path and trim off filename
var slashpos=pathPrefix.lastIndexOf("/"); if (slashpos==-1) slashpos=pathPrefix.lastIndexOf("\\");
if (slashpos!=-1 && slashpos!=pathPrefix.length-1) pathPrefix=pathPrefix.substr(0,slashpos+1);
if (this.fileExists(getLocalPath(pathPrefix+locallink))) return locallink;
}
// no embedded data, no local (or not found), fallback to remote URL (if any)
if (remotelink.length)
return remotelink;
return ""; // attachment URL doesn't resolve
}
//}}}
//{{{
if (config.macros.attach.init_formatters==undefined) config.macros.attach.init_formatters=function() {
if (this.initialized) return;
// find the formatter for "image" and replace the handler
for (var i=0; i<config.formatters.length && config.formatters[i].name!="image"; i++);
if (i<config.formatters.length) config.formatters[i].handler=function(w) {
if (!this.lookaheadRegExp) // fixup for TW2.0.x
this.lookaheadRegExp = new RegExp(this.lookahead,"mg");
this.lookaheadRegExp.lastIndex = w.matchStart;
var lookaheadMatch = this.lookaheadRegExp.exec(w.source)
if(lookaheadMatch && lookaheadMatch.index == w.matchStart) // Simple bracketted link
{
var e = w.output;
if(lookaheadMatch[5])
{
var link = lookaheadMatch[5];
// ELS -------------
if (!config.formatterHelpers.isExternalLink) // fixup for TW2.0.x
var external=!store.tiddlerExists(link)&&!store.isShadowTiddler(link);
else
var external=config.formatterHelpers.isExternalLink(link);
if (external)
{
if (config.macros.attach.isAttachment(link))
{
e = createExternalLink(w.output,link);
e.href=config.macros.attach.getAttachment(link);
e.title = config.macros.attach.linkTooltip + link;
}
else
e = createExternalLink(w.output,link);
}
else
e = createTiddlyLink(w.output,link,false,null,w.isStatic);
// ELS -------------
addClass(e,"imageLink");
}
var img = createTiddlyElement(e,"img");
if(lookaheadMatch[1])
img.align = "left";
else if(lookaheadMatch[2])
img.align = "right";
if(lookaheadMatch[3])
img.title = lookaheadMatch[3];
img.src = lookaheadMatch[4];
// ELS -------------
if (config.macros.attach.isAttachment(lookaheadMatch[4]))
img.src=config.macros.attach.getAttachment(lookaheadMatch[4]);
// ELS -------------
w.nextMatch = this.lookaheadRegExp.lastIndex;
}
}
//}}}
//{{{
// find the formatter for "prettyLink" and replace the handler
for (var i=0; i<config.formatters.length && config.formatters[i].name!="prettyLink"; i++);
if (i<config.formatters.length) {
var v=version.major+.1*version.minor+.01*version.revision;
if (v>=2.13) {
config.formatters[i].handler=function(w)
{
this.lookaheadRegExp.lastIndex = w.matchStart;
var lookaheadMatch = this.lookaheadRegExp.exec(w.source);
if(lookaheadMatch && lookaheadMatch.index == w.matchStart)
{
var e;
var text = lookaheadMatch[1];
if(lookaheadMatch[3])
{
// Pretty bracketted link
var link = lookaheadMatch[3];
if (config.macros.attach.isAttachment(link))
{
e = createExternalLink(w.output,link);
e.href=config.macros.attach.getAttachment(link);
e.title=config.macros.attach.linkTooltip+link;
}
else e = (!lookaheadMatch[2] && config.formatterHelpers.isExternalLink(link))
? createExternalLink(w.output,link)
: createTiddlyLink(w.output,link,false,null,w.isStatic);
}
else
{
e = createTiddlyLink(w.output,text,false,null,w.isStatic);
}
createTiddlyText(e,text);
w.nextMatch = this.lookaheadRegExp.lastIndex;
}
}
} else { // FALLBACK for TW2.1.2 and earlier
config.formatters[i].handler=function(w)
{
if (!this.lookaheadRegExp) // fixup for TW2.0.x
this.lookaheadRegExp = new RegExp(this.lookahead,"mg");
this.lookaheadRegExp.lastIndex = w.matchStart;
var lookaheadMatch = this.lookaheadRegExp.exec(w.source)
if(lookaheadMatch && lookaheadMatch.index == w.matchStart)
{
var e;
var text = lookaheadMatch[1];
if (lookaheadMatch[2]) // Simple bracketted link
{
e = createTiddlyLink(w.output,text,false,null,w.isStatic);
}
else if(lookaheadMatch[3]) // Pretty bracketted link
{
var link = lookaheadMatch[4];
// ELS -------------
if (!config.formatterHelpers.isExternalLink) // fixup for TW2.0.x
var external=!store.tiddlerExists(link)&&!store.isShadowTiddler(link);
else
var external=config.formatterHelpers.isExternalLink(link);
if (external)
{
if (config.macros.attach.isAttachment(link))
{
e = createExternalLink(w.output,link);
e.href=config.macros.attach.getAttachment(link);
e.title = config.macros.attach.linkTooltip + link;
}
else
e = createExternalLink(w.output,link);
}
else
e = createTiddlyLink(w.output,link,false,null,w.isStatic);
// ELS -------------
}
createTiddlyText(e,text);
w.nextMatch = this.lookaheadRegExp.lastIndex;
}
}
} // END FALLBACK
} // if "prettyLink" formatter found
this.initialized=true;
}
//}}}
//{{{
config.macros.attach.init_formatters(); // load time init
//}}}
//{{{
if (TiddlyWiki.prototype.coreGetRecursiveTiddlerText==undefined) {
TiddlyWiki.prototype.coreGetRecursiveTiddlerText = TiddlyWiki.prototype.getRecursiveTiddlerText;
TiddlyWiki.prototype.getRecursiveTiddlerText = function(title,defaultText,depth) {
return config.macros.attach.isAttachment(title)?
config.macros.attach.getAttachment(title):this.coreGetRecursiveTiddlerText.apply(this,arguments);
}
}
//}}}
/***
|Name|AttachFilePluginInfo|
|Source|http://www.TiddlyTools.com/#AttachFilePlugin|
|Documentation|http://www.TiddlyTools.com/#AttachFilePluginInfo|
|Version|3.8.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|Documentation for AttachFilePlugin|
Store or link binary files (such as jpg, gif, pdf or even mp3) within your TiddlyWiki document and then use them as images or links from within your tiddler content.
!!!!!Inline interface (live)
>see [[AttachFile]] (shadow tiddler)
><<tiddler AttachFile>>
!!!!!Syntax
<<<
''To display the attach file control panel, simply view the [[AttachFile]] shadow tiddler that is automatically created by the plugin, and contains an instance of the inline control panel.''. Or, you can write:
{{{
<<attach inline>>
}}}
in any tiddler to display the control panel embedded within that tiddler. Note: you can actually use any unique identifier in place of the "inline" keyword. Each unique id creates a separate instance of the controls. If the same ID is used in more than one tiddler, then the control panel is automatically moved to the most recently rendered location. Or, you can write:
{{{
<<attach>>
}}}
(with no ID parameter) in SidebarOptions. This adds a command link that opens the controls as a floating panel, positioned directly to the left of the sidebar.
<<<
!!!!!Usage
<<<
Binary file content can be stored in three different locations:
#embedded in the attachment tiddler (encoded as base64)
#on your filesystem (a 'local link' path/filename)
#on a web server (a 'remote link' URL)
The plugin creates an "attachment tiddler" for each file you attach. Regardless of where you store the binary content, your document can refer to the attachment tiddler rather than using a direct file or URL reference in your embedded image or external links, so that changing document locations will not require updating numerous tiddlers or copying files from one system to another.
> Important note: As of version 3.6.0, in order to //render// images and other binary attachments created with this plugin, you must also install [[AttachFilePluginFormatters]], which extends the behavior of the TiddlyWiki core formatters for embedded images ({{{[img[tooltip|image]]}}}), linked embedded images ({{{[img[tooltip|image][link]]}}}), and external/"pretty" links ({{{[[label|link]]}}}), so that these formatter will process references to attachment tiddlers as if a normal file reference had been provided. |
When you attach a file, a tiddler (tagged with<<tag attachment>>) is generated (using the source filename as the tiddler's title). The tiddler contains //''base64 text-encoded binary data''//, surrounded by {{{/%...%/}}} comment markers (so they are not visible when viewing the tiddler). The tiddler also includes summary details about the file: when it was attached, by whom, etc. and, if the attachment is an image file (jpg, gif, or png), the image is automatically displayed below the summary information.
>Note: although you can edit an attachment tiddler, ''don't change any of the encoded content below the attachment header'', as it has been prepared for use in the rest of your document, and even changing a single character can make the attachment unusable. //If needed, you ''can'' edit the header information or even the MIME type declaration in the attachment data, but be very careful not to change any of the base64-encoded binary data.//
With embedded data, your TW document can be completely self-contained...unfortunately, embedding just a few moderately-sized binary files using base64 text-encoding can dramatically increase the size of your document. To avoid this problem, you can create attachment tiddlers that define external local filesystem (file://) and/or remote web server (http://) 'reference' links, without embedding the binary data directly in the tiddler (i.e., uncheck "embed data" in the 'control panel').
These links provide an alternative source for the binary data: if embedded data is not found (or you are running on Internet Explorer, which does not currently support using embedded data), then the plugin tries the local filesystem reference. If a local file is not found, then the remote reference (if any) is used. This "fallback" approach also lets you 'virtualize' the external links in your document, so that you can access very large binary content such as PDFs, MP3's, and even *video* files, by using just a 'remote reference link' without embedding any data or downloading huge files to your hard disk.
Of course, when you //do// download an attached file, the local copy will be used instead of accessing a remote server each time, thereby saving bandwidth and allowing you to 'go mobile' without having to edit any tiddlers to alter the link locations...
<<<
!!!!!Syntax / Examples
<<<
To embed attached files as images or link to them from other tiddlers, use the standard ~TiddlyWiki image syntax ({{{[img[tooltip|filename]]}}}), linked image syntax ({{{[img[tooltip|filename][tiddlername]]}}}) , or "external link" syntax ({{{[[text|URL]]}}}), replacing the filename or URL that is normally entered with the title of an attachment tiddler.
embedded image data:
>{{{[img[Meow|AttachFileSample]]}}}
>[img[Meow|AttachFileSample]]
embedded image data with link to larger remote image:
>{{{[img[click for larger view|AttachFileSample][AttachFileSample2]]}}}
>[img[click for larger view|AttachFileSample][AttachFileSample2]]
'external' link to embedded image data:
>{{{[[click to view attachment|AttachFileSample]]}}}
>[[click to view attachment|AttachFileSample]]
'external' link to remote image:
>{{{[[click to view attachment|AttachFileSample2]]}}}
>[[click to view attachment|AttachFileSample2]]
regular ~TiddlyWiki links to attachment tiddlers:
>{{{[[AttachFileSample]]}}} [[AttachFileSample]]
>{{{[[AttachFileSample2]]}}} [[AttachFileSample2]]
<<<
!!!!!Defining MIME types
<<<
When you select a source file, a ''[[MIME|http://en.wikipedia.org/wiki/MIME]]'' file type is automatically suggested, based on filename extension. The AttachFileMIMETypes tiddler defines the list of MIME types that will be recognized by the plugin. Each MIME type definition consists of exactly two lines of text: the official MIME type designator (e.g., "text/plain", "image/gif", etc.), and a space-separated list of file extensions associated with that type. List entries are separated by "----" (horizontal rules).
<<<
!!!!!Known Limitations
<<<
Internet Explorer does not support the data: URI scheme, and cannot use the //embedded// data to render images or links. However, you can still use the local/remote link definitions to create file attachments that are stored externally. In addition, while it is relatively easy to read local //text// files, reading binary files is not directly supported by IE's FileSystemObject (FSO) methods, and other file I/O techniques are subject to security barriers or require additional MS proprietary technologies (like ASP or VB) that make implementation more difficult. As a result, you cannot //create// new attachment tiddlers using IE.
<<<
!!!!!Installation
<<<
Import (or copy/paste) the following tiddlers into your document:
* [[AttachFilePlugin]] (tagged with <<tag systemConfig>>)
* [[AttachFilePluginFormatters]] ("runtime distribution library") (tagged with <<tag systemConfig>>)
* [[AttachFileSample]] and [[AttachFileSample2]] //(tagged with <<tag attachment>>)//
* [[AttachFileMIMETypes //(defines binary file types)//
> Important note: As of version 3.6.0, in order to //render// images and other binary attachments created with this plugin, you must also install [[AttachFilePluginFormatters]], which extends the behavior of the TiddlyWiki core formatters for embedded images ({{{[img[tooltip|image]]}}}), linked embedded images ({{{[img[tooltip|image][link]]}}}), and external/"pretty" links ({{{[[label|link]]}}}), so that these formatter will process references to attachment tiddlers as if a normal file reference had been provided. |
<<<
!!!!!Revisions
<<<
2008.04.09 [3.8.0] in onChangeSource(), if source matches current document folder, use relative reference for local link. Also, disable 'embed' when using IE (which //still// doesn't support data: URI)
2008.04.07 [3.7.3] fixed typo in HTML for 'local file link' so that clicking in input field doesn't erase current path/file (if any)
2008.04.07 [3.7.2] auto-create AttachFile shadow tiddler for inline interface
2008.01.08 [*.*.*] plugin size reduction: documentation moved to ...Info
2007.12.04 [*.*.*] update for TW2.3.0: replaced deprecated core functions, regexps, and macros
2007.12.03 [3.7.1] in createAttachmentTiddler(), added optional "noshow" flag to suppress display of newly created tiddlers.
2007.10.29 [3.7.0] code reduction: removed support for built-in upload to server... on-line hosting of binary attachments is left to the document author, who can upload/host files using 3rd-party web-based services (e.g. www.flickr.com, ) or stand-alone applications (e.g., FTP).
2007.10.28 [3.6.0] code reduction: removed duplicate definition of image and prettyLink formatters. Rendering of attachment tiddlers now //requires// installation of AttachFilePluginFormatters
2007.03.01 [3.5.3] use apply() to invoke hijacked function
2007.02.25 [3.5.2] in hijack of "prettyLink", fix version check for TW2.2 compatibility (prevent incorrect use of fallback handler)
2007.01.09 [3.5.1] onClickAttach() refactored to create separate createAttachmentTiddler() API for use with FileDropPluginHandlers
2006.11.30 [3.5.0] in getAttachment(), for local references, add check for file existence and fallback to remote URL if local file not found. Added fileExists() to encapsulate FF vs. IE local file test function (IE FSO object code is TBD).
2006.11.29 [3.4.8] in hijack for PrettyLink, 'simple bracketed link' opens tiddler instead of external link to attachment
2006.11.29 [3.4.7] in readFile(), added try..catch around initWithPath() to handle invalid/non-existent paths better.
2006.11.09 [3.4.6] REAL FIX for TWv2.1.3: incorporate new TW2.1.3 core "prettyLink" formatter regexp handling logic and check for version < 2.1.3 with fallback to old plugin code. Also, cleanup table layout in HTML (added "border:0" directly to table elements to override stylesheet)
2006.11.08 [3.4.5] TEMPORARY FIX for TWv2.1.3: disable hijack of wikiLink formatter due to changes in core wikiLink regexp definition. //Links to attachments are broken, but you can still use {{{[img[TiddlerName]]}}} to render attachments as images, as well as {{{background:url('[[TiddlerName]]')}}} in CSS declarations for background images.//
2006.09.10 [3.4.4] update formatters for 2.1 compatibility (use this.lookaheadRegExp instead of temp variable)
2006.07.24 [3.4.3] in prettyLink formatter, added check for isShadowTiddler() to fix problem where shadow links became external links.
2006.07.13 [3.4.2] in getAttachment(), fixed stripping of newlines so data: used in CSS will work
2006.05.21 [3.4.1] in getAttachment(), fixed substring() to extract data: URI (was losing last character, which broken rendering of SOME images)
2006.05.20 [3.4.0] hijack core getRecursiveTiddlerText() to support rendering attachments in stylesheets (e.g. {{{url([[AttachFileSample]])}}})
2006.05.20 [3.3.6] add "description" feature to easily include notes in attachment tiddler (you can always edit to add them later... but...)
2006.05.19 [3.3.5] add "attach as" feature to change default name for attachment tiddlers. Also, new optional param to specify tiddler name (disables editing)
2006.05.16 [3.3.0] completed XMLHttpRequest handling for GET or POST to configurable server scripts
2006.05.13 [3.2.0] added interface for upload feature. Major rewrite of code for clean object definitions. Major improvements in UI interaction and validation.
2006.05.09 [3.1.1] add wikifer support for using attachments in links from "linked image" syntax: {{{[img[tip|attachment1][attachment2]]}}}
2006.05.09 [3.1.0] lots of code changes: new options for attachments that use embedded data and/or links to external files (local or remote)
2006.05.03 [3.0.2] added {{{/%...%/}}} comments around attachment data to hide it when viewing attachment tiddler.
2006.02.05 [3.0.1] wrapped wikifier hijacks in initAttachmentFormatters() function to eliminate globals and avoid FireFox 1.5.0.1 crash bug when referencing globals
2005.12.27 [3.0.0] Update for TW2.0. Automatically add 'excludeMissing' tag to attachments
2005.12.16 [2.2.0] Dynamically create/remove attachPanel as needed to ensure only one instance of interface elements exists, even if there are multiple instances of macro embedding.
2005.11.20 [2.1.0] added wikifier handler extensions for "image" and "prettyLink" to render tiddler attachments
2005.11.09 [2.0.0] begin port from old ELS Design plugin/adaptation hybrid based on ~TW1.2.33
2005.08.05 [1.1.0] moved CSS and HTML definitions into plugin code tiddler instead of using separate tiddlers
2005.07.27 [1.0.2] core update 1.2.29: custom overlayStyleSheet() replaced with new core setStylesheet()
2005.07.23 [1.0.1] added parameter checks and corrected addNotification() usage
2005.07.20 [1.0.0] Initial Release
<<<
/***
|Name|CalendarPlugin|
|Source|http://www.TiddlyTools.com/#CalendarPlugin|
|Version|2008.06.17|
|Author|Eric Shulman|
|Original Author|SteveRumsby|
|License|unknown|
|~CoreVersion|2.1|
|Type|plugin|
|Requires||
|Overrides||
|Options|##Configuration|
|Description|display monthly and yearly calendars|
NOTE: For enhanced date display (including popups), you must also install [[DatePlugin]]
!!!!!Usage:
<<<
|{{{<<calendar>>}}}|Produce a full-year calendar for the current year|
|{{{<<calendar year>>}}}|Produce a full-year calendar for the given year|
|{{{<<calendar year month>>}}}|Produce a one-month calendar for the given month and year|
|{{{<<calendar thismonth>>}}}|Produce a one-month calendar for the current month|
|{{{<<calendar lastmonth>>}}}|Produce a one-month calendar for last month|
|{{{<<calendar nextmonth>>}}}|Produce a one-month calendar for next month|
<<<
!!!!!Configuration:
<<<
|''First day of week:''<br>{{{config.options.txtCalFirstDay}}}|<<option txtCalFirstDay>>|(Monday = 0, Sunday = 6)|
|''First day of weekend:''<br>{{{config.options.txtCalStartOfWeekend}}}|<<option txtCalStartOfWeekend>>|(Monday = 0, Sunday = 6)|
<<option chkDisplayWeekNumbers>> Display week numbers //(note: Monday will be used as the start of the week)//
|''Week number display format:''<br>{{{config.options.txtWeekNumberDisplayFormat }}}|<<option txtWeekNumberDisplayFormat >>|
|''Week number link format:''<br>{{{config.options.txtWeekNumberLinkFormat }}}|<<option txtWeekNumberLinkFormat >>|
<<<
!!!!!Revisions
<<<
2008.06.17: added support for config.macros.calendar.todaybg
2008.02.27: in handler(), DON'T set hard-coded default date format, so that *customized* value (pre-defined in config.macros.calendar.journalDateFmt is used.
2008.02.17: in createCalendarYear(), fix next/previous year calculation (use parseInt() to convert to numeric value). Also, use journalDateFmt for date linking when NOT using [[DatePlugin]].
2008.02.16: in createCalendarDay(), week numbers now created as TiddlyLinks, allowing quick creation/navigation to 'weekly' journals (based on request from Kashgarinn)
2008.01.08: in createCalendarMonthHeader(), "month year" heading is now created as TiddlyLink, allowing quick creation/navigation to 'month-at-a-time' journals
2007.11.30: added "return false" to onclick handlers (prevent IE from opening blank pages)
2006.08.23: added handling for weeknumbers (code supplied by Martin Budden (see "wn**" comment marks). Also, incorporated updated by Jeremy Sheeley to add caching for reminders (see [[ReminderMacros]], if installed)
2005.10.30: in config.macros.calendar.handler(), use "tbody" element for IE compatibility. Also, fix year calculation for IE's getYear() function (which returns '2005' instead of '105'). Also, in createCalendarDays(), use showDate() function (see [[DatePlugin]], if installed) to render autostyled date with linked popup. Updated calendar stylesheet definition: use .calendar class-specific selectors, add text centering and margin settings
2006.05.29: added journalDateFmt handling
<<<
***/
/***
!!!!!Code section:
***/
//{{{
version.extensions.calendar = { major: 0, minor: 7, revision: 0, date: new Date(2008, 6, 17)};
if(config.options.txtCalFirstDay == undefined)
config.options.txtCalFirstDay = 0;
if(config.options.txtCalStartOfWeekend == undefined)
config.options.txtCalStartOfWeekend = 5;
if(config.options.chkDisplayWeekNumbers == undefined)//wn**
config.options.chkDisplayWeekNumbers = false;
if(config.options.chkDisplayWeekNumbers)
config.options.txtCalFirstDay = 0;
if(config.options.txtWeekNumberDisplayFormat == undefined)//wn**
config.options.txtWeekNumberDisplayFormat = "w0WW";
if(config.options.txtWeekNumberLinkFormat == undefined)//wn**
config.options.txtWeekNumberLinkFormat = "YYYY-w0WW";
config.macros.calendar = {};
config.macros.calendar.monthnames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
config.macros.calendar.daynames = ["M", "T", "W", "T", "F", "S", "S"];
config.macros.calendar.todaybg = "#ccccff";
config.macros.calendar.weekendbg = "#c0c0c0";
config.macros.calendar.monthbg = "#e0e0e0";
config.macros.calendar.holidaybg = "#ffc0c0";
config.macros.calendar.journalDateFmt = "DD MMM YYYY";
config.macros.calendar.monthdays = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
config.macros.calendar.holidays = [ ]; // Not sure this is required anymore - use reminders instead
//}}}
//{{{
function calendarIsHoliday(date) // Is the given date a holiday?
{
var longHoliday = date.formatString("0DD/0MM/YYYY");
var shortHoliday = date.formatString("0DD/0MM");
for(var i = 0; i < config.macros.calendar.holidays.length; i++) {
if(config.macros.calendar.holidays[i] == longHoliday || config.macros.calendar.holidays[i] == shortHoliday)
return true;
}
return false;
}
//}}}
//{{{
config.macros.calendar.handler = function(place,macroName,params) {
var calendar = createTiddlyElement(place, "table", null, "calendar", null);
var tbody = createTiddlyElement(calendar, "tbody", null, null, null);
var today = new Date();
var year = today.getYear();
if (year<1900) year+=1900;
// get format for journal link by reading from SideBarOptions (ELS 5/29/06 - based on suggestion by Martin Budden)
var text = store.getTiddlerText("SideBarOptions");
var re = new RegExp("<<(?:newJournal)([^>]*)>>","mg"); var fm = re.exec(text);
if (fm && fm[1]!=null) { var pa=fm[1].readMacroParams(); if (pa[0]) this.journalDateFmt = pa[0]; }
if (params[0] == "thismonth") {
cacheReminders(new Date(year, today.getMonth(), 1, 0, 0), 31);
createCalendarOneMonth(tbody, year, today.getMonth());
}
else if (params[0] == "lastmonth") {
var month = today.getMonth()-1; if (month==-1) { month=11; year--; }
cacheReminders(new Date(year, month, 1, 0, 0), 31);
createCalendarOneMonth(tbody, year, month);
}
else if (params[0] == "nextmonth") {
var month = today.getMonth()+1; if (month>11) { month=0; year++; }
cacheReminders(new Date(year, month, 1, 0, 0), 31);
createCalendarOneMonth(tbody, year, month);
} else {
if (params[0]) year = params[0];
if(params[1]) {
cacheReminders(new Date(year, params[1]-1, 1, 0, 0), 31);
createCalendarOneMonth(tbody, year, params[1]-1);
} else {
cacheReminders(new Date(year, 0, 1, 0, 0), 366);
createCalendarYear(tbody, year);
}
}
window.reminderCacheForCalendar = null;
}
//}}}
//{{{
//This global variable is used to store reminders that have been cached
//while the calendar is being rendered. It will be renulled after the calendar is fully rendered.
window.reminderCacheForCalendar = null;
//}}}
//{{{
function cacheReminders(date, leadtime)
{
if (window.findTiddlersWithReminders == null) return;
window.reminderCacheForCalendar = {};
var leadtimeHash = [];
leadtimeHash [0] = 0;
leadtimeHash [1] = leadtime;
var t = findTiddlersWithReminders(date, leadtimeHash, null, 1);
for(var i = 0; i < t.length; i++) {
//just tag it in the cache, so that when we're drawing days, we can bold this one.
window.reminderCacheForCalendar[t[i]["matchedDate"]] = "reminder:" + t[i]["params"]["title"];
}
}
//}}}
//{{{
function createCalendarOneMonth(calendar, year, mon)
{
var row = createTiddlyElement(calendar, "tr", null, null, null);
createCalendarMonthHeader(calendar, row, config.macros.calendar.monthnames[mon] + " " + year, true, year, mon);
row = createTiddlyElement(calendar, "tr", null, null, null);
createCalendarDayHeader(row, 1);
createCalendarDayRowsSingle(calendar, year, mon);
}
//}}}
//{{{
function createCalendarMonth(calendar, year, mon)
{
var row = createTiddlyElement(calendar, "tr", null, null, null);
createCalendarMonthHeader(calendar, row, config.macros.calendar.monthnames[mon] + " " + year, false, year, mon);
row = createTiddlyElement(calendar, "tr", null, null, null);
createCalendarDayHeader(row, 1);
createCalendarDayRowsSingle(calendar, year, mon);
}
//}}}
//{{{
function createCalendarYear(calendar, year)
{
var row;
row = createTiddlyElement(calendar, "tr", null, null, null);
var back = createTiddlyElement(row, "td", null, null, null);
var backHandler = function() {
removeChildren(calendar);
createCalendarYear(calendar, parseInt(year)-1);
return false; // consume click
};
createTiddlyButton(back, "<", "Previous year", backHandler);
back.align = "center";
var yearHeader = createTiddlyElement(row, "td", null, "calendarYear", year);
yearHeader.align = "center";
yearHeader.setAttribute("colSpan",config.options.chkDisplayWeekNumbers?22:19);//wn**
var fwd = createTiddlyElement(row, "td", null, null, null);
var fwdHandler = function() {
removeChildren(calendar);
createCalendarYear(calendar, parseInt(year)+1);
return false; // consume click
};
createTiddlyButton(fwd, ">", "Next year", fwdHandler);
fwd.align = "center";
createCalendarMonthRow(calendar, year, 0);
createCalendarMonthRow(calendar, year, 3);
createCalendarMonthRow(calendar, year, 6);
createCalendarMonthRow(calendar, year, 9);
}
//}}}
//{{{
function createCalendarMonthRow(cal, year, mon)
{
var row = createTiddlyElement(cal, "tr", null, null, null);
createCalendarMonthHeader(cal, row, config.macros.calendar.monthnames[mon], false, year, mon);
createCalendarMonthHeader(cal, row, config.macros.calendar.monthnames[mon+1], false, year, mon);
createCalendarMonthHeader(cal, row, config.macros.calendar.monthnames[mon+2], false, year, mon);
row = createTiddlyElement(cal, "tr", null, null, null);
createCalendarDayHeader(row, 3);
createCalendarDayRows(cal, year, mon);
}
//}}}
//{{{
function createCalendarMonthHeader(cal, row, name, nav, year, mon)
{
var month;
if (nav) {
var back = createTiddlyElement(row, "td", null, null, null);
back.align = "center";
back.style.background = config.macros.calendar.monthbg;
var backMonHandler = function() {
var newyear = year;
var newmon = mon-1;
if(newmon == -1) { newmon = 11; newyear = newyear-1;}
removeChildren(cal);
cacheReminders(new Date(newyear, newmon , 1, 0, 0), 31);
createCalendarOneMonth(cal, newyear, newmon);
return false; // consume click
};
createTiddlyButton(back, "<", "Previous month", backMonHandler);
month = createTiddlyElement(row, "td", null, "calendarMonthname")
createTiddlyLink(month,name,true);
month.setAttribute("colSpan", config.options.chkDisplayWeekNumbers?6:5);//wn**
var fwd = createTiddlyElement(row, "td", null, null, null);
fwd.align = "center";
fwd.style.background = config.macros.calendar.monthbg;
var fwdMonHandler = function() {
var newyear = year;
var newmon = mon+1;
if(newmon == 12) { newmon = 0; newyear = newyear+1;}
removeChildren(cal);
cacheReminders(new Date(newyear, newmon , 1, 0, 0), 31);
createCalendarOneMonth(cal, newyear, newmon);
return false; // consume click
};
createTiddlyButton(fwd, ">", "Next month", fwdMonHandler);
} else {
month = createTiddlyElement(row, "td", null, "calendarMonthname", name)
month.setAttribute("colSpan",config.options.chkDisplayWeekNumbers?8:7);//wn**
}
month.align = "center";
month.style.background = config.macros.calendar.monthbg;
}
//}}}
//{{{
function createCalendarDayHeader(row, num)
{
var cell;
for(var i = 0; i < num; i++) {
if (config.options.chkDisplayWeekNumbers) createTiddlyElement(row, "td");//wn**
for(var j = 0; j < 7; j++) {
var d = j + (config.options.txtCalFirstDay - 0);
if(d > 6) d = d - 7;
cell = createTiddlyElement(row, "td", null, null, config.macros.calendar.daynames[d]);
if(d == (config.options.txtCalStartOfWeekend-0) || d == (config.options.txtCalStartOfWeekend-0+1))
cell.style.background = config.macros.calendar.weekendbg;
}
}
}
//}}}
//{{{
function createCalendarDays(row, col, first, max, year, mon) {
var i;
if (config.options.chkDisplayWeekNumbers){
if (first<=max) {
var ww = new Date(year,mon,first);
var td=createTiddlyElement(row, "td");//wn**
var link=createTiddlyLink(td,ww.formatString(config.options.txtWeekNumberLinkFormat),false);
link.appendChild(document.createTextNode(ww.formatString(config.options.txtWeekNumberDisplayFormat)));
}
else createTiddlyElement(row, "td", null, null, null);//wn**
}
for(i = 0; i < col; i++)
createTiddlyElement(row, "td", null, null, null);
var day = first;
for(i = col; i < 7; i++) {
var d = i + (config.options.txtCalFirstDay - 0);
if(d > 6) d = d - 7;
var daycell = createTiddlyElement(row, "td", null, null, null);
var isaWeekend = ((d == (config.options.txtCalStartOfWeekend-0) || d == (config.options.txtCalStartOfWeekend-0+1))? true:false);
if(day > 0 && day <= max) {
var celldate = new Date(year, mon, day);
// ELS 2005.10.30: use <<date>> macro's showDate() function to create popup
// ELS 5/29/06 - use journalDateFmt
if (window.showDate)
showDate(daycell,celldate,"popup","DD",config.macros.calendar.journalDateFmt,true, isaWeekend);
else {
if(isaWeekend) daycell.style.background = config.macros.calendar.weekendbg;
var title = celldate.formatString(config.macros.calendar.journalDateFmt);
if(calendarIsHoliday(celldate))
daycell.style.background = config.macros.calendar.holidaybg;
var now=new Date();
if ((now-celldate>=0) && (now-celldate<86400000)) // is today?
daycell.style.background = config.macros.calendar.todaybg;
if(window.findTiddlersWithReminders == null) {
var link = createTiddlyLink(daycell, title, false);
link.appendChild(document.createTextNode(day));
} else
var button = createTiddlyButton(daycell, day, title, onClickCalendarDate);
}
}
day++;
}
}
//}}}
//{{{
// We've clicked on a day in a calendar - create a suitable pop-up of options.
// The pop-up should contain:
// * a link to create a new entry for that date
// * a link to create a new reminder for that date
// * an <hr>
// * the list of reminders for that date
// NOTE: The following code is only used when [[DatePlugin]] is not present
function onClickCalendarDate(e)
{
var button = this;
var date = button.getAttribute("title");
var dat = new Date(date.substr(6,4), date.substr(3,2)-1, date.substr(0, 2));
date = dat.formatString(config.macros.calendar.journalDateFmt);
var popup = createTiddlerPopup(this);
popup.appendChild(document.createTextNode(date));
var newReminder = function() {
var t = store.getTiddlers(date);
displayTiddler(null, date, 2, null, null, false, false);
if(t) {
document.getElementById("editorBody" + date).value += "\n<<reminder day:" + dat.getDate() +
" month:" + (dat.getMonth()+1) + " year:" + (dat.getYear()+1900) + " title: >>";
} else {
document.getElementById("editorBody" + date).value = "<<reminder day:" + dat.getDate() +
" month:" + (dat.getMonth()+1) +" year:" + (dat.getYear()+1900) + " title: >>";
}
return false; // consume click
};
var link = createTiddlyButton(popup, "New reminder", null, newReminder);
popup.appendChild(document.createElement("hr"));
var t = findTiddlersWithReminders(dat, [0,14], null, 1);
for(var i = 0; i < t.length; i++) {
link = createTiddlyLink(popup, t[i].tiddler, false);
link.appendChild(document.createTextNode(t[i].tiddler));
}
return false; // consume click
}
//}}}
//{{{
function calendarMaxDays(year, mon)
{
var max = config.macros.calendar.monthdays[mon];
if(mon == 1 && (year % 4) == 0 && ((year % 100) != 0 || (year % 400) == 0)) max++;
return max;
}
//}}}
//{{{
function createCalendarDayRows(cal, year, mon)
{
var row = createTiddlyElement(cal, "tr", null, null, null);
var first1 = (new Date(year, mon, 1)).getDay() -1 - (config.options.txtCalFirstDay-0);
if(first1 < 0) first1 = first1 + 7;
var day1 = -first1 + 1;
var first2 = (new Date(year, mon+1, 1)).getDay() -1 - (config.options.txtCalFirstDay-0);
if(first2 < 0) first2 = first2 + 7;
var day2 = -first2 + 1;
var first3 = (new Date(year, mon+2, 1)).getDay() -1 - (config.options.txtCalFirstDay-0);
if(first3 < 0) first3 = first3 + 7;
var day3 = -first3 + 1;
var max1 = calendarMaxDays(year, mon);
var max2 = calendarMaxDays(year, mon+1);
var max3 = calendarMaxDays(year, mon+2);
while(day1 <= max1 || day2 <= max2 || day3 <= max3) {
row = createTiddlyElement(cal, "tr", null, null, null);
createCalendarDays(row, 0, day1, max1, year, mon); day1 += 7;
createCalendarDays(row, 0, day2, max2, year, mon+1); day2 += 7;
createCalendarDays(row, 0, day3, max3, year, mon+2); day3 += 7;
}
}
//}}}
//{{{
function createCalendarDayRowsSingle(cal, year, mon)
{
var row = createTiddlyElement(cal, "tr", null, null, null);
var first1 = (new Date(year, mon, 1)).getDay() -1 - (config.options.txtCalFirstDay-0);
if(first1 < 0) first1 = first1+ 7;
var day1 = -first1 + 1;
var max1 = calendarMaxDays(year, mon);
while(day1 <= max1) {
row = createTiddlyElement(cal, "tr", null, null, null);
createCalendarDays(row, 0, day1, max1, year, mon); day1 += 7;
}
}
//}}}
//{{{
setStylesheet(".calendar, .calendar table, .calendar th, .calendar tr, .calendar td { text-align:center; } .calendar, .calendar a { margin:0px !important; padding:0px !important; }", "calendarStyles");
//}}}
// // override cookie settings for CalendarPlugin:
//{{{
config.options.txtCalFirstDay=6;
config.options.txtCalStartOfWeekend=5;
//}}}
// // override internal default settings for CalendarPlugin:
//{{{
config.macros.calendar.journalDateFmt="DDD MMM 0DD YYYY";
//}}}
! Cardinalidade (geral)
Dois conjuntos têm o mesmo tamanho se existe uma correspondência (1:1 e onto) entre eles.
Pode-se dizer que os dois conjuntos são equivalentes (cardinalidades iguais definem classes de equivalências entre conjuntos).
! Conjunto infinito
Um conjunto é infinito sempre que for equivalente a um subconjunto próprio de si mesmo.
Caso contrário, o conjunto é finito.
! Conjunto infinito contável
é aquele pra o qual existe uma correspondência com o conjunto dos números naturais
$NN={0,1,2,3,...}$
Dize-se que sua cardinalidade é $aleph_0$
! Exemplo
Seja $NN^**={1,2,3,...}$ o conjunto dos naturais positivos e E o conjunto dos naturais positivos pares.
Mostre que ambos possuem o mesmo tamanho.
> Determinar f(n)=2n
>
> Mostrar que f é injetora e sobrejetora (de $NN$ em E)
> f(a)=2a
> f(b)=2b
>
> Se $a ne b => 2a ne 2b => f(a) ne f(b)$
>
> Seja x elemento de E, $x/2$ é um natural positivo, então $f(x/2)=x$.
Conjunto contável é o que tem o mesmo tamanho que $NN$.
! Exemplo - números racionais
$QQ^+$ são os racionais positivos
$QQ^+={m/n|m,n in NN^+}
Provar que $QQ$ tem o mesmo tamanho que $NN$.
> Encontre uma função (enumeração) que associe a cada elemento de $QQ$, um de $NN$.
Construir uma matriz com $i/j$, onde i é a linha e j é a coluna
$ ((1/1, 1/2, 1/3, 1/4, 1/5, ...), (2/1, 2/2, 2/3, 2/4, 2/5, ...), (3/1, 3/2, 3/3, 3/4, 3/5, ...), (4/1, 4/2, 4/3, 4/4, 4/5, ...),(5/1, ... , , , , ))$
Escrever os elementos da matriz na forma de lista, percorrendo na diagonal, pulando elementos repetidos.
$ (1/1, 2/1, 1/2, 3/1, 1/3, 4/1, 3/2, 2/3, 1/4, 5/1, 1/5, ...)$
! Exemplo - números reais
Mostrar que $RR$ é incontável.
Prova por contradição.
Supor $f: NN -> RR$ uma correspondência. (condição necessária e suficiente para $RR$ ser contável)
Encontrar $x in RR, x ne n, AA n in NN$, considerar caso $0<x<1$, assim podemos escrever x na forma
0,DDDDDD.... onde D é um dígito de 0 a 9
Por exemplo, o início de uma enumeração poderia ser
f(1)=0,100100100... (dízima periódica)
f(2)=0,31415926 ... (pi dividido por 10)
f(3)=0,44444444.... (dízima periódica)
f(4)=0,000500000 ... (racional)
...
Vamos construir o número real x de forma que o j-ésimo dígito de x é diferente do j-ésimo dígito de f(j), assim garantimos que x é diferente de todos os demais números.
Assim, x é construído diferente de f(1), f(2), f(3), f(4) porque o dígito j o faz diferente de f(j).
Escolhemos arbitrariamente os dígitos de 1 a 4 desde que respeitem a regra dada e sejam diferentes de 0 e 9.
0,4256...
Como x é um número real, então, por hipótese, deve haver uma enumeração f(n)=x pra ele.
Entretanto, por construção, o n-ésimo dígito de x deve ser diferente do n-ésimo dígito de f(n) e portanto $x ne f(n)$, o que nos leva a uma contradição.
Assim, a hipótese de que os números reais são enumeráveis é absurda.
! Noção da cardinalidade de $RR$
Vamos encontrar uma bijeção entre o intervalo $[0,1]$ e o conjunto $2^NN$.
Escrevendo um número real entre 0 e 1 na forma binária:
$r=0,d_1 d_2 d_3 d_4...$
São infinitos dígitos $d_i$ com valor 0 ou 1.
Cada dígito corresponde a um número natural.
A correspondência procurada é dada pela função $f:2^NN -> [0,1]$
$f(c)=0,d_1d_2d_3d_4...d_i... | d_i={stackrel(1 " se " i in c)(0 " caso contrário")$
> Exercício:
>
> O conjunto $NN xx NN$ é enumerável.
>
> O conjunto $2^NN$ não é conjunto enumerável.
>
> A cardinalidade do intervalo [0,1] é igual à cardinalidade de $RR$.
>
<<tiddler NextTiddler with: [[Estruturas de dados]]>>
/***
|Name:|CloseOnCancelPlugin|
|Description:|Closes the tiddler if you click new tiddler then cancel. Default behaviour is to leave it open|
|Version:|3.0.1 ($Rev: 3861 $)|
|Date:|$Date: 2008-03-08 10:53:09 +1000 (Sat, 08 Mar 2008) $|
|Source:|http://mptw.tiddlyspot.com/#CloseOnCancelPlugin|
|Author:|Simon Baird <simon.baird@gmail.com>|
|License:|http://mptw.tiddlyspot.com/#TheBSDLicense|
***/
//{{{
merge(config.commands.cancelTiddler,{
handler_mptw_orig_closeUnsaved: config.commands.cancelTiddler.handler,
handler: function(event,src,title) {
this.handler_mptw_orig_closeUnsaved(event,src,title);
if (!store.tiddlerExists(title) && !store.isShadowTiddler(title))
story.closeTiddler(title,true);
return false;
}
});
//}}}
<<tabs txtTabDicas "Sintaxe" "Sintaxe do TiddlyWiki" [[Sintaxe do Wiki]] "Equações" "Sintaxe das equações" [[Sintaxe das Equações]] "Gráficos" "Sintaxe dos gráficos" [[Sintaxe dos Gráficos]]>>
[[Dicas]]
/%
|Name|DigitalClock|
|Source|http://www.TiddlyTools.com/#DigitalClock|
|Version|1.0.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|script|
|Requires|InlineJavascriptPlugin|
|Overrides||
|Description|display current time with automatic LIVE update|
Usage: <<tiddler DigitalClock with: format tick>>
where 'format' is any TiddlyWiki date/time formatting string
and 'tick' is the time in seconds between display updates (default=1sec)
For example, use:
<< ... "0hh:0mm" 60>>
to show hours and minutes only, updated once per minute
%/<script>
window.DigitalClock_tick=function(id){
var e=document.getElementById(id); if (!e) return;
e.title='click to '+(e.paused?'RESUME':'PAUSE')+' clock display';
if (e.paused) return;
e.innerHTML=new Date().formatString(e.fmt);
setTimeout('window.DigitalClock_tick('+id+')',e.tick*1000);
}
var e=createTiddlyElement(place,'a',new Date().getTime()+Math.random());
e.onclick=function(){this.paused=!this.paused;window.DigitalClock_tick(this.id);}
e.style.cursor='pointer';
e.fmt=('$1'=='$'+'1')?'hh12:0mm:0ss am':'$1';
e.tick=('$2'=='$'+'2')?'1':'$2';
window.DigitalClock_tick(e.id);
</script>
!Expressão lógica
$L_1={ttx in Sigma_1^** | ttx=ttw a, ttw in Sigma_1^**, a in {1,3,5,7,9} }, Sigma_1={0,1,2,3,...,9}$
!Representação recursiva
$Sigma_2={a,b}$ - Strings de comprimento par começando por a.
(i) aa e ab $in L_2$
(ii) Se $ttu in L_2$, então $ttu a a, ttu ab, ttu ba$ e $ttu b b in L_2$
(iii) $ttu in L_2$ apenas se pode ser obtida a partir dos elementos de (i) por um número finito de aplicações de (ii)
!!Exemplo
$Sigma_3={a,b}$ - Cada b é imediatamente precedido por um a.
(i) $epsilon in L_3$
(ii) $ttu in L_3 => ttu a, ttu a b in L_3$
(iii) $ttu in L_3$ apenas se obtido a partir de $epsilon$ por um número finito de aplicações do passo recursivo (ii).
!Concatenação de Linguagens
A concatenação das linguagens X e Y, denotada XY, é a linguagem
$XY={ttu ttv | ttu in X " e " ttv in Y}$
A concatenação de X consigo n vexes é denotada $X^n$. $X^0={epsilon}$.
Exemplo:
X={a,b,c} e Y={abb,ba}, então
XY={aabb, babb, cabb, aba, bba, cba}
$X^0={epsilon}$
$X^1$=X={a,b,c}
$X^2$=XX={aa,ab,ac,ba,bb,bc,ca,cb,cc}
$X uu Y$ = {a, b, c, abb, ba}
! Fechamento de Kleene
Se X é um conjunto, então
$X^**= uuu_(i=0)^(oo) X^i$
$X^+ = uuu_(i=1)^(oo) X^i$
Notar que $X^+=XX^**$
$ X={a,b,c} => X^**={epsilon, a, b, c, a a, a b, a c, b a, b b, b c, c a, c b, c c, a a a, ...}$
$X^+$ não contém o $epsilon$
!Reverso da linguagem
$X^R={ttu^R|u in X}$
!Representação da lingaugem com operadores
Linguagem das strings que contém a substring bb
{a,b}*{bb}{a,b}*
Cadeias que começam e terminam com a e que contém pelo menos um b
{a}{a,b}*{b}{a,b}*{a}
Cadeias sobre {a,b} começando com aa ou terminando com bb
{aa}{a,b}* U {a,b}*{bb}
Cadeias sobre {a,b} de comprimento par.
{aa,bb,ab,ba}*
! Seqüências
(7,21,57) - tupla (no caso uma 3-tupla ou tripla), seqüência finita.
(2,4,6,8,10,...) - seqüência infinita.
Diferentemente dos conjuntos, a ordem dos elementos é importante e pode haver repetições de elementos.
! Grafos
Um grafo G=(V,E) é uma tupla onde
V é um conjunto de vértices e
$E sub V xx V$ é o conjunto de arestas que conectam 2 vértices. (uma relação)
Exemplo
V={1,2,3,4,5}
E={(1,2),(2,3),(3,4),(4,5),(5,1)}
Exemplo (desconexo)
V={1,2,3,4,5}
E={(n,m) | n+m=4 ou n+m=7}
> Desenhar os grafos representando os vértices por círculos e as arestas por cenexões entre círculos.
!!Definições
sub-grafo: subconjunto de V e de E que também é um grafo.
caminho: seqüência de vértices $ v_1, v_2 ... v_k, k ge 1$ tais que existam as arestas, isto é, $(v_i, v_(i+1)) in E$
com $1 le i < K$. O comprimento do caminho é k-1.
ciclo: caminho com $v_1=v_k$
árvore: grafo sem ciclos
! Conectividade
Um grafo é conexo se existe caminho de um vértice a qualquer outro
> Utilizar o fecho de E para obter a conectividade
Grafos disjuntos: não existe caminho para dois nós escolhidos.
! Grafo direcionado (digrafo)
Pares ordenados $v_1 |-> v_2$ formam as arestas ou arcos.
Exemplo $G=({1,2,3,4}, {i |-> j | i<j})$
Exemplo:
$V={1,2,3,4,5,6}$
$E={(1|->2),(1|->5),(2|->1),(2|->4),(5|->4),(5|->6),(6|->1),(6|->3)}$
Grau de um vértice é o número de arestas ligadas ao vértice.
Grau de entrada do nó (fan-in) é o número de arcos destinados ao nó.
Grau de saída do nó (fan-out) é o número de arcos originados no nó.
! Árvore com raiz e indução de direções
A escolha de um vértice como raiz na ´rvore induz um direcionamento das arestas, representando a relação "é filho de".
Árvore binária: máximo número de filhos por nó é 2.
Os filhos podem ser ordenados: filho à esquerda e filho à direita.
<<tiddler NextTiddler with: [[Tipos de Demonstração]]>>
/***
|Name:|ExtentTagButtonPlugin|
|Description:|Adds a New tiddler button in the tag drop down|
|Version:|3.2 ($Rev: 3861 $)|
|Date:|$Date: 2008-03-08 10:53:09 +1000 (Sat, 08 Mar 2008) $|
|Source:|http://mptw.tiddlyspot.com/#ExtendTagButtonPlugin|
|Author:|Simon Baird <simon.baird@gmail.com>|
|License|http://mptw.tiddlyspot.com/#TheBSDLicense|
***/
//{{{
window.onClickTag_mptw_orig = window.onClickTag;
window.onClickTag = function(e) {
window.onClickTag_mptw_orig.apply(this,arguments);
var tag = this.getAttribute("tag");
var title = this.getAttribute("tiddler");
// Thanks Saq, you're a genius :)
var popup = Popup.stack[Popup.stack.length-1].popup;
createTiddlyElement(createTiddlyElement(popup,"li",null,"listBreak"),"div");
wikify("<<newTiddler label:'New tiddler' tag:'"+tag+"'>>",createTiddlyElement(popup,"li"));
return false;
}
//}}}
/***
|FileDropPlugin|h
|author : BradleyMeck|
|version : 0.1.1|
|date : Nov 13 2006|
|usage : drag a file onto the TW to have it be made into a tiddler|
|browser(s) supported : Mozilla|
Note: this version has been 'tweaked' by Eric Shulman (http://www.TiddlyTools.com) to add suspend/resume notification handling to improve performance when multiple files are dropped at once.
!Trouble Shooting
*If the plugin does not seem to work, open up the page "about:config" (just type it in the address bar) and make sure @@color(blue):signed.applets.codebase_principal_support@@ is set to @@color(blue):true@@
!Revisions
*Multiple File Dropping API updated, to end all capturing events after yours return a value that makes if(myFunctionsReturnValue) evaluate to true
*Added support for multiple file drop handlers
**Use the config.macros.fileDrop.addEventListener(@@color(green):String Flavor@@, @@color(green):Function handler(nsiFile){}@@, @@color(green):Boolean addToFront@@) function
***Standard Flavor is "application/x-moz-file"
***addToFront gives your handler priority over all others at time of add
*Old plugin would disallow drops of text vetween applications because it didn't check if the transfer was a file.
!Example Handler
*Adds simple file import control, add this to a tiddler tagged {{{systemConfig}}} to make file dropping work
{{{
config.macros.fileDrop.addEventListener("application/x-moz-file",function(nsiFile)
{
if(
confirm("You have dropped the file \""+nsiFile.path+"\" onto the page, it will be imported as a tiddler. Is that ok?")
)
{
var newDate = new Date();
var title = prompt("what would you like to name the tiddler?");
store.saveTiddler(title,title,loadFile(nsiFile.path),config.options.txtUserName,newDate,[]);
}
return true;
})
}}}
!Example Handler without popups and opening the tiddler on load
*Adds simple file import control, add this to a tiddler tagged {{{systemConfig}}} to make file dropping work
{{{
config.macros.fileDrop.addEventListener("application/x-moz-file",function(nsiFile)
{
var newDate = new Date();
store.saveTiddler(nsiFile.path,nsiFile.path,loadFile(nsiFile.path),config.options.txtUserName,newDate,[]);
story.displayTiddler(null,nsiFile.path)
return true;
})
}}}
!Code
***/
//{{{
config.macros.fileDrop = {version : {major : 0, minor : 0, revision: 1}};
config.macros.fileDrop.customDropHandlers = [];
config.macros.fileDrop.dragDropHandler = function(evt) {
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
// Load in the native DragService manager from the browser.
var dragService = Components.classes["@mozilla.org/widget/dragservice;1"].getService(Components.interfaces.nsIDragService);
// Load in the currently-executing Drag/drop session.
var dragSession = dragService.getCurrentSession();
// Create an instance of an nsITransferable object using reflection.
var transferObject = Components.classes["@mozilla.org/widget/transferable;1"].createInstance();
// Bind the object explicitly to the nsITransferable interface. We need to do this to ensure that
// methods and properties are present and work as expected later on.
transferObject = transferObject.QueryInterface(Components.interfaces.nsITransferable);
// I've chosen to add only the x-moz-file MIME type. Any type can be added, and the data for that format
// will be retrieved from the Drag/drop service.
transferObject.addDataFlavor("application/x-moz-file");
// Get the number of items currently being dropped in this drag/drop operation.
var numItems = dragSession.numDropItems;
// ELS 2007.12.03: performance improvement when dropping multiple files
if (numItems>1) {
clearMessage();
displayMessage("Reading "+numItems+" files...");
store.suspendNotifications();
}
for (var i = 0; i < numItems; i++)
{
// Get the data for the given drag item from the drag session into our prepared
// Transfer object.
dragSession.getData(transferObject, i);
// We need to pass in Javascript 'Object's to any XPConnect method which
// requires OUT parameters. The out value will then be saved as a new
// property called Object.value.
var dataObj = {};
var dropSizeObj = {};
for(var ind = 0; ind < config.macros.fileDrop.customDropHandlers.length; ind++)
{
var item = config.macros.fileDrop.customDropHandlers[ind];
if(dragSession.isDataFlavorSupported(item.flavor))
{
transferObject.getTransferData(item.flavor, dataObj, dropSizeObj);
var droppedFile = dataObj.value.QueryInterface(Components.interfaces.nsIFile);
// Display all of the returned parameters with an Alert dialog.
var result = item.handler.call(item,droppedFile);
// Since the event is handled, prevent it from going to a higher-level event handler.
evt.stopPropagation();
evt.preventDefault();
if(result){break;}
}
}
}
// ELS 2007.12.03: performance improvement and feedback after dropping multiple files
if (numItems>1) {
store.resumeNotifications();
store.notifyAll();
displayMessage(numItems+" files have been processed");
}
}
if(!window.event)
{
// Register the event handler, and set the 'capture' flag to true so we get this event
// before it bubbles up through the browser.
window.addEventListener("dragdrop", config.macros.fileDrop.dragDropHandler , true);
}
config.macros.fileDrop.addEventListener = function(paramflavor,func,inFront)
{
var obj = {};
obj.flavor = paramflavor;
obj.handler = func;
if(!inFront)
{config.macros.fileDrop.customDropHandlers.push(obj);}
else{config.macros.fileDrop.customDropHandlers.shift(obj);}
}
//}}}
/***
|Name|FileDropPluginConfig|
|Source|http://www.TiddlyTools.com/#FileDropPluginConfig|
|Version|1.5.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|FileDropPlugin, AttachFilePlugin|
|Overrides||
|Options|##Configuration|
|Description|Adds drag-and-drop handlers for creating binary attachments or directory lists|
__TiddlyTools FileDrop+AttachFile extended handler:__
* use just filename instead of whole path as tiddler title
* check for existing tiddler and prompt for new name
* handle folder drops (drops each file or creates a file list in a tiddler)
* use AttachFilePlugin if MIME type is not text/plain
* autotag created tiddlers (e.g., "temporary", "dropped", etc.)
* option to suppress automatic display of newly created tiddlers
* suspend/resume notifications when handling multiple files (performance improvement)
!!!!!Configuration
<<<
<<option chkFileDropTrimFilename>> Omit file extensions from tiddler titles when creating new tiddlers
{{{usage: <<option chkFileDropTrimFilename>> }}}
<<option chkFileDropDisplay>> Automatically display newly created tiddlers
{{{usage: <<option chkFileDropDisplay>> }}}
Tag newly created tiddlers with: <<option txtFileDropTags>>
{{{usage: <<option txtFileDropTags>>}}}
__FileDrop+AttachFile configuration options:__
<<option chkFileDropAttachEncodeData>> Encode binary file data as embedded "base64" text
{{{usage: <<option chkFileDropAttachEncodeData>> }}}
...for binary files smaller than: <<option txtFileDropAttachDataLimit>> bytes
{{{usage: <<option txtFileDropAttachDataLimit>>}}}
See [[FileDropPlugin]] for more documentation on handler implementation specifics, including sample code for default drop handlers.
<<<
!!!!!Code
***/
//{{{
if (config.options.chkFileDropAttachEncodeData==undefined)
config.options.chkFileDropAttachEncodeData=true;
if (config.options.txtFileDropAttachDataLimit==undefined)
config.options.txtFileDropAttachDataLimit=32768;
if (config.options.txtFileDropTags==undefined)
config.options.txtFileDropTags="";
if (config.options.chkFileDropDisplay==undefined)
config.options.chkFileDropDisplay=true;
if (config.options.chkFileDropTrimFilename==undefined)
config.options.chkFileDropTrimFilename=false;
config.macros.fileDrop.addEventListener("application/x-moz-file",function(nsiFile)
{
var header="Index of %0\n^^(as of %1)^^\n|!filename| !size | !modified |\n";
var item="|[[%0|%1]]| %2|%3|\n";
var footer="Total of %0 bytes in %1 files\n";
var now=new Date();
var files=[nsiFile];
if (nsiFile.isDirectory()) {
var folder=nsiFile.directoryEntries;
var files=[];
while (folder.hasMoreElements()) {
var f=folder.getNext().QueryInterface(Components.interfaces.nsILocalFile);
if (f instanceof Components.interfaces.nsILocalFile && !f.isDirectory()) files.push(f);
}
var msg=nsiFile.path.replace(/\\/g,"/")+"\n\n";
msg+="contains "+files.length+" files... ";
msg+="select OK to attach all files or CANCEL to create a list...";
if (!confirm(msg)) { // create a list in a tiddler
var title=nsiFile.leafName; // tiddler name is last directory name in path
while (title && title.length && store.tiddlerExists(title)) {
if (confirm(config.messages.overwriteWarning.format([title]))) break; // use existing title
title=prompt("Please enter a different tiddler title for this file",nsiFile.path.replace(/\\/g,"/"));
}
if (!title || !title.length) return true; // aborted by user... we're done!
var text=header.format([nsiFile.path.replace(/\\/g,"/"),now.toLocaleString()]);
var total=0;
for (var i=0; i<files.length; i++) { var f=files[i];
var name=f.leafName;
if (config.options.chkFileDropTrimFilename)
{ var p=name.split("."); if (p.length>1) p.pop(); name=p.join("."); }
var path="file:///"+f.path.replace(/\\/g,"/");
var size=f.fileSize; total+=size;
var when=new Date(f.lastModifiedTime).formatString("YYYY.0MM.0DD 0hh:0mm:0ss");
text+=item.format([name,path,size,when]);
}
text+=footer.format([total,files.length]);
var newtags=config.options.txtFileDropTags?config.options.txtFileDropTags.readBracketedList():[];
store.saveTiddler(null,title,text,config.options.txtUserName,now,newtags);
if (config.options.chkFileDropDisplay) story.displayTiddler(null,title);
return true;
}
}
if (files.length>1) store.suspendNotifications();
for (i=0; i<files.length; i++) {
var file=files[i];
if (file.isDirectory()) continue; // skip over nested directories
var type="text/plain";
var title=file.leafName; // tiddler name is file name
if (config.options.chkFileDropTrimFilename)
{ var p=title.split("."); if (p.length>1) p.pop(); title=p.join("."); }
var path=file.path;
var size=file.fileSize;
while (title && title.length && store.tiddlerExists(title)) {
if (confirm(config.messages.overwriteWarning.format([title]))) break; // use existing title
title=prompt("Please enter a different tiddler title for this file",path.replace(/\\/g,"/"));
}
if (!title || !title.length) continue; // cancelled by user... skip this file
if (config.macros.attach) {
type=config.macros.attach.getMIMEType(file.leafName,"");
if (!type.length)
type=prompt("Unrecognized file type. Please enter a MIME type for this file","text/plain");
if (!type||!type.length) continue; // cancelled by user... skip this file
}
var newtags=config.options.txtFileDropTags?config.options.txtFileDropTags.readBracketedList():[];
if (type=="text/plain")
store.saveTiddler(null,title,loadFile(path),config.options.txtUserName,now,newtags);
else {
// only encode data if enabled and file is smaller than limit. Default is 32768 (32K) bytes.
var embed=config.options.chkFileDropAttachEncodeData
&& file.fileSize<config.options.txtFileDropAttachDataLimit;
newtags.push("attachment"); newtags.push("excludeMissing");
// if file is in current document folder, remove path prefix and use relative reference
var localfile=path;
var h=document.location.href; folder=getLocalPath(decodeURIComponent(h.substr(0,h.lastIndexOf("/")+1)));
if (localfile.substr(0,folder.length)==folder) localfile='./'+localfile.substr(folder.length);
config.macros.attach.createAttachmentTiddler(path,
now.formatString(config.macros.timeline.dateFormat),
"attached by FileDropPlugin", newtags,
title, embed, true, false, localfile, "", type,!config.options.chkFileDropDisplay);
}
if (config.options.chkFileDropDisplay) story.displayTiddler(null,title);
}
if (files.length>1) { store.resumeNotifications(); store.notifyAll(); }
if (window.FFDEBUG) console.log(new Date()-now);
return true;
})
//}}}
/***
|Name|FoldHeadingsPlugin|
|Source|http://www.TiddlyTools.com/#FoldHeadingsPlugin|
|Version|1.0.2|
|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|automatically turn headings into slider-like panels that can be folded/unfolded with a single click|
This plugin defines a macro that automatically converts heading-formatted content into sliders that let you expand/collapse their content by clicking on individual headings.
!!!!!Usage
<<<
{{{
<<foldHeadings opened|closed tag tag tag...>>
}}}
where: ''opened'' or ''closed'' is a keyword indicating the initial state of the sections (default: opened), and ''tag tag tag...'' is an optional list of tags to match, so that the foldable effect is only applied to tiddlers that contain one (or more) of the indicated tags.
When you place the macro in a tiddler, any heading-formatted content (i.e, "!" through "!!!!!") in that tiddler will automatically become //'fold-able'//, allowing you to expand/collapse the content that follows each heading simply by clicking on that heading. Each content section begins with the first element following a heading, and continues until either another heading is found or the end of the tiddler is reached. For example:
{{{
<<foldHeadings closed>>
}}}
is embedded in ''this'' tiddler in order to make all the headings it contains 'fold-able'. Note that the macro has been placed at the //end// of the tiddler because it only operates on *rendered* content. Thus, only headings that //precede// it in the same tiddler will become fold-able, as any headings that //follow// it are not actually rendered until //after// the macro has been processed.
You can further limit the effect of the macro within the tiddler by surrounding several headings in a "CSS class wrapper" ("""{{classname{...}}}""") or other containing DOM element (e.g., """@@display:inline;...@@""") and then embedding the {{{<<foldHeadings>>}}} macro inside that container (at the end)... only those headings that are also within that container will be made fold-able, instead of converting ''all'' the headings in that tiddler.
Conversely, if you want the fold-able ability to apply to the headings in //all// tiddlers, ''without having to alter //any// of those individual tiddlers'', you can add the macro to the end of your [[ViewTemplate]], so that it will be invoked after the content in each tiddler has been rendered, causing all headings they contain to automatically become fold-able. For example:
{{{
<span macro="foldHeadings closed"></span>
}}}
You can also limit this effect to selected tiddlers by specifying one or more tags as additional macro parameters. For example:
{{{
<span macro="foldHeadings closed systemConfig"></span>
}}}
is only applied to headings contained in //plugin tiddlers// (i.e., tiddlers tagged with <<tag systemConfig>>), while headings in other tiddlers remain unaffected by the macro, even though it is embedded in the common [[ViewTemplate]] definition.
<<<
!!!!!Revisions
<<<
2007.12.06 [1.0.2] fix handling for empty sections when checking for sliderPanel/floatingPanel
2007.12.02 [1.0.1] fix handling when content following a heading is already a sliderPanel/floatingPanel
2007.12.01 [1.0.0] initial release
<<<
!!!!!Code
***/
//{{{
version.extensions.FoldHeadings= {major: 1, minor: 0, revision: 2, date: new Date(2007,12,6)};
config.macros.foldHeadings = {
guideText: "opened|closed className",
showtip: "click to show '%0'",
hidetip: "click to hide '%0'",
showlabel: "more...",
hidelabel: "[x]",
html: "<span style='float:right;text-weight:normal;font-size:80%;' class='TiddlyLinkExisting'>%0 </span>",
handler: function(place,macroName,params) {
var show=params[0] && params.shift().toLowerCase()!="closed";
if (params.length) { // if filtering by tag(s)
var here=story.findContainingTiddler(place);
if (here) var tid=store.getTiddler(here.getAttribute("tiddler"));
if (!tid || !tid.tags.containsAny(params)) return; // in a tiddler and not tagged... do nothing...
}
var elems=place.parentNode.getElementsByTagName("*");
var heads=[]; for (var i=0; i<elems.length; i++) { // get non-foldable heading elements
var n=elems[i].nodeName; var foldable=hasClass(elems[i],"foldable");
if ((n=="H1"||n=="H2"||n=="H3"||n=="H4"||n=="H5")&&!foldable)
heads.push(elems[i]);
}
for (var i=0; i<heads.length; i++) { var h=heads[i]; // for each heading element...
// find start/end of section content (up to next heading or end of content)
var start=end=h.nextSibling; while (end && end.nextSibling) {
var n=end.nextSibling.nodeName.toUpperCase();
if (n=="H1"||n=="H2"||n=="H3"||n=="H4"||n=="H5") break;
end=end.nextSibling;
}
if (start && hasClass(start,"sliderPanel")||hasClass(start,"floatingPanel")) continue; // heading is already a slider!
var span=createTiddlyElement(null,"span",null,"sliderPanel"); // create container
span.style.display=show?"inline":"none"; // set initial display state
h.parentNode.insertBefore(span,start); // and insert it following the heading element
// move section elements into container...
var e=start; while (e) { var next=e.nextSibling; span.insertBefore(e,null); if (e==end) break; e=next; }
// set heading label/tip/cursor...
h.title=(show?this.hidetip:this.showtip).format([h.textContent])
h.innerHTML=this.html.format([show?this.hidelabel:this.showlabel])+h.innerHTML;
h.style.cursor='pointer';
addClass(h,"foldable"); // so we know it been done (and to add extra styles)
h.onclick=function() {
var panel=this.nextSibling; var show=panel.style.display=="none";
// update panel display state
if (config.options.chkAnimate) anim.startAnimating(new Slider(panel,show));
else panel.style.display = show?"inline":"none";
// update heading label/tip
this.removeChild(this.firstChild); // remove existing label
var fh=config.macros.foldHeadings; // abbreviation for readability...
this.title=(show?fh.hidetip:fh.showtip).format([this.textContent])
this.innerHTML=fh.html.format([show?fh.hidelabel:fh.showlabel])+this.innerHTML;
}
}
}
}
//}}}
// //<<foldHeadings closed>>
/***
|Name|FontSizePlugin|
|Created by|SaqImtiaz|
|Location|http://tw.lewcid.org/#FontSizePlugin|
|Version|1.0|
|Requires|~TW2.x|
!Description:
Resize tiddler text on the fly. The text size is remembered between sessions by use of a cookie.
You can customize the maximum and minimum allowed sizes.
(only affects tiddler content text, not any other text)
Also, you can load a TW file with a font-size specified in the url.
Eg: http://tw.lewcid.org/#font:110
!Demo:
Try using the font-size buttons in the sidebar, or in the MainMenu above.
!Installation:
Copy the contents of this tiddler to your TW, tag with systemConfig, save and reload your TW.
Then put {{{<<fontSize "font-size:">>}}} in your SideBarOptions tiddler, or anywhere else that you might like.
!Usage
{{{<<fontSize>>}}} results in <<fontSize>>
{{{<<fontSize font-size: >>}}} results in <<fontSize font-size:>>
!Customizing:
The buttons and prefix text are wrapped in a span with class fontResizer, for easy css styling.
To change the default font-size, and the maximum and minimum font-size allowed, edit the config.fontSize.settings section of the code below.
!Notes:
This plugin assumes that the initial font-size is 100% and then increases or decreases the size by 10%. This stepsize of 10% can also be customized.
!History:
*27-07-06, version 1.0 : prevented double clicks from triggering editing of containing tiddler.
*25-07-06, version 0.9
!Code
***/
//{{{
config.fontSize={};
//configuration settings
config.fontSize.settings =
{
defaultSize : 100, // all sizes in %
maxSize : 200,
minSize : 40,
stepSize : 10
};
//startup code
var fontSettings = config.fontSize.settings;
if (!config.options.txtFontSize)
{config.options.txtFontSize = fontSettings.defaultSize;
saveOptionCookie("txtFontSize");}
setStylesheet(".tiddler .viewer {font-size:"+config.options.txtFontSize+"%;}\n","fontResizerStyles");
setStylesheet("#contentWrapper .fontResizer .button {display:inline;font-size:105%; font-weight:bold; margin:0 1px; padding: 0 3px; text-align:center !important;}\n .fontResizer {margin:0 0.5em;}","fontResizerButtonStyles");
//macro
config.macros.fontSize={};
config.macros.fontSize.handler = function (place,macroName,params,wikifier,paramString,tiddler)
{
var sp = createTiddlyElement(place,"span",null,"fontResizer");
sp.ondblclick=this.onDblClick;
if (params[0])
createTiddlyText(sp,params[0]);
createTiddlyButton(sp,"+","increase font-size",this.incFont);
createTiddlyButton(sp,"=","reset font-size",this.resetFont);
createTiddlyButton(sp,"–","decrease font-size",this.decFont);
}
config.macros.fontSize.onDblClick = function (e)
{
if (!e) var e = window.event;
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
return false;
}
config.macros.fontSize.setFont = function ()
{
saveOptionCookie("txtFontSize");
setStylesheet(".tiddler .viewer {font-size:"+config.options.txtFontSize+"%;}\n","fontResizerStyles");
}
config.macros.fontSize.incFont=function()
{
if (config.options.txtFontSize < fontSettings.maxSize)
config.options.txtFontSize = (config.options.txtFontSize*1)+fontSettings.stepSize;
config.macros.fontSize.setFont();
}
config.macros.fontSize.decFont=function()
{
if (config.options.txtFontSize > fontSettings.minSize)
config.options.txtFontSize = (config.options.txtFontSize*1) - fontSettings.stepSize;
config.macros.fontSize.setFont();
}
config.macros.fontSize.resetFont=function()
{
config.options.txtFontSize=fontSettings.defaultSize;
config.macros.fontSize.setFont();
}
config.paramifiers.font =
{
onstart: function(v)
{
config.options.txtFontSize = v;
config.macros.fontSize.setFont();
}
};
//}}}
# [[AttachFilePackage]]
# [[CalendarPlugin]]
# [[CalendarPluginConfig]]
# [[CloseOnCancelPlugin]]
# [[Dicas]]
# [[ExtendTagButtonPlugin]]
# [[FoldHeadingsPlugin]]
# [[FontSizePlugin]]
# [[HideWhenPlugin]]
# [[IDE Area]]
# [[InstantTimestampPlugin]]
# [[LessBackupsPlugin]]
# [[List of Toolbar Commands]]
# [[MoveTiddlerToTop]]
# [[MptwBlack]]
# [[MptwBlue]]
# [[MptwConfigPlugin]]
# [[MptwGreen]]
# [[MptwRed]]
# [[MptwRoundTheme]]
# [[MptwSmoke]]
# [[MptwStandardTheme]]
# [[MptwTeal]]
# [[MptwTrimTheme]]
# [[MptwUpgradeURL]]
# [[MptwUserConfigPlugin]]
# [[MyToolbarIcons]]
# [[NewHerePlugin]]
# [[NewMeansNewPlugin]]
# [[PrettyDatesPlugin]]
# [[QuickOpenTagPlugin]]
# [[RenameTagsPlugin]]
# [[SVGIncluderPlugin]]
# [[SelectThemePlugin]]
# [[TableSortingPlugin]]
# [[TagglyTaggingPlugin]]
# [[TidIDEPackage]]
# [[ToggleSideBarMacro]]
# [[ToggleTagPlugin]]
# [[ToolbarIconsPlugin]]
# [[smiley]]
# systemConfig
To get started with this blank TiddlyWiki, you'll need to modify the following tiddlers:
* SiteTitle & SiteSubtitle: The title and subtitle of the site, as shown above (after saving, they will also appear in the browser title bar)
* MainMenu: The menu (usually on the left)
* DefaultTiddlers: Contains the names of the tiddlers that you want to appear when the TiddlyWiki is opened
You'll also need to enter your username for signing your edits: <<option txtUserName>>
See also [[MPTW]].
/***
|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);
}}
});
//}}}
/***
|Name|InlineJavascriptPlugin|
|Source|http://www.TiddlyTools.com/#InlineJavascriptPlugin|
|Documentation|http://www.TiddlyTools.com/#InlineJavascriptPluginInfo|
|Version|1.9.3|
|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.
!!!!!Documentation
>see [[InlineJavascriptPluginInfo]]
!!!!!Revisions
<<<
2008.06.11 [1.9.3] added $(...) function as 'shorthand' convenience syntax for document.getElementById()
2008.03.03 [1.9.2] corrected declaration of wikifyPlainText() for 'TW 2.1.x compatibility fallback' (fixes Safari "parse error")
2008.02.23 [1.9.1] in onclick function, use string instead of array for 'bufferedHTML' attribute on link element (fixes IE errors)
2008.02.21 [1.9.0] 'onclick' scripts now allow returned text (or document.write() calls) to be wikified into a span that immediately follows the onclick link. Also, added default 'return false' handling if no return value provided (prevents HREF from being triggered -- return TRUE to allow HREF to be processed). Thanks to Xavier Verges for suggestion and preliminary code.
|please see [[InlineJavascriptPluginInfo]] for additional revision details|
2005.11.08 [1.0.0] initial release
<<<
!!!!!Code
***/
//{{{
version.extensions.inlineJavascript= {major: 1, minor: 9, revision: 3, date: new Date(2008,6,11)};
config.formatters.push( {
name: "inlineJavascript",
match: "\\<script",
lookahead: "\\<script(?: src=\\\"((?:.|\\n)*?)\\\")?(?: label=\\\"((?:.|\\n)*?)\\\")?(?: title=\\\"((?:.|\\n)*?)\\\")?(?: key=\\\"((?:.|\\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) {
var src=lookaheadMatch[1];
var label=lookaheadMatch[2];
var tip=lookaheadMatch[3];
var key=lookaheadMatch[4];
var show=lookaheadMatch[5];
var code=lookaheadMatch[6];
if (src) { // 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 = src;
document.body.appendChild(script); document.body.removeChild(script);
}
if (code) { // there is script code
if (show) // show inline script code in tiddler output
wikify("{{{\n"+lookaheadMatch[0]+"\n}}}\n",w.output);
if (label) { // 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",wikifyPlainText(label));
var fixup=code.replace(/document.write\s*\(/gi,'place.bufferedHTML+=(');
link.code="function _out(place){"+fixup+"\n};_out(this);"
link.tiddler=w.tiddler;
link.onclick=function(){
this.bufferedHTML="";
try{ var r=eval(this.code);
if(this.bufferedHTML.length || (typeof(r)==="string")&&r.length)
var s=this.parentNode.insertBefore(document.createElement("span"),this.nextSibling);
if(this.bufferedHTML.length)
s.innerHTML=this.bufferedHTML;
if((typeof(r)==="string")&&r.length) {
wikify(r,s,null,this.tiddler);
return false;
} else return r!==undefined?r:false;
} catch(e){alert(e.description||e.toString());return false;}
};
link.setAttribute("title",tip||"");
var URIcode='javascript:void(eval(decodeURIComponent(%22(function(){try{';
URIcode+=encodeURIComponent(encodeURIComponent(code.replace(/\n/g,' ')));
URIcode+='}catch(e){alert(e.description||e.toString())}})()%22)))';
link.setAttribute("href",URIcode);
link.style.cursor="pointer";
if (key) link.accessKey=key.substr(0,1); // single character only
}
else { // run inline script code
var fixup=code.replace(/document.write\s*\(/gi,'place.innerHTML+=(');
var code="function _out(place){"+fixup+"\n};_out(w.output);"
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;
}
}
} )
//}}}
// // Backward-compatibility for TW2.1.x and earlier
//{{{
if (typeof(wikifyPlainText)=="undefined") window.wikifyPlainText=function(text,limit,tiddler) {
if(limit > 0) text = text.substr(0,limit);
var wikifier = new Wikifier(text,formatter,null,tiddler);
return wikifier.wikifyPlain();
}
//}}}
// // $(...) function: 'shorthand' convenience syntax for document.getElementById()
//{{{
if (typeof($)=="undefined") { // avoid redefinition
function $() {
var elements=new Array();
for (var i=0; i<arguments.length; i++) {
var element=arguments[i];
if (typeof element=='string') element=document.getElementById(element);
if (arguments.length==1) return element;
elements.push(element);
}
return elements;
}
}
//}}}
/***
|Name|InlineJavascriptPluginInfo|
|Source|http://www.TiddlyTools.com/#InlineJavascriptPlugin|
|Documentation|http://www.TiddlyTools.com/#InlineJavascriptPluginInfo|
|Version|1.9.3|
|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|documentation|
|Requires||
|Overrides||
|Description|Documentation for InlineJavascriptPlugin|
''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
<<<
This plugin adds wiki syntax for surrounding tiddler content with {{{<script>}}} and {{{</script>}}} markers, so that it can be recognized as embedded javascript code.
<script show>
/* javascript code goes here... */
</script>Every time the tiddler content is rendered, the javascript code is automatically evaluated, allowing you to invoke 'side-effect' processing and/or produce dynamically-generated content that is then inserted into the tiddler content, immediately following the script (see below). By including the optional ''show'' keyword as the final parameter in a {{{<script>}}} marker, the plugin will also include the script source code in the output that it displays in the tiddler. This is helpful when creating examples for documentation purposes (such as used in this tiddler!)
__''Deferred execution from an 'onClick' link''__
<script label="click here" title="mouseover tooltip text" key="X" show>
/* javascript code goes here... */
alert('you clicked on the link!');
</script>
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, and a {{{key="X"}}} parameter to specify an //access key// (which must be a //single// letter or numeric digit only).
__''Loading scripts from external source files''__
<script src="URL" show>
/* optional javascript code goes here... */
</script>You can also load javascript directly 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.
In addition to loading the javascript from the external file, you can also use this feature to invoke javascript code contained within the {{{<script>...</script>}}} markers. This code is invoked //after// the external script file has been processed, and can make immediate use of the functions and/or global variables defined by the external script file.
>Note: To ensure that your javascript functions are always available when needed, you should load the libraries from a tiddler that is rendered as soon as your TiddlyWiki document is opened, such as MainMenu. For example: put your {{{<script src="..."></script>}}} syntax into a separate 'library' tiddler (e.g., LoadScripts), and then add {{{<<tiddler LoadScripts>>}}} to MainMenu so that the library is loaded before any other tiddlers that rely upon the functions it defines.
>
>Normally, loading external javascript in this way does not produce any direct output, and should not have any impact on the appearance of your MainMenu. However, if your LoadScripts tiddler contains notes or other visible content, you can suppress this output by using 'inline CSS' in the MainMenu, like this: {{{@@display:none;<<tiddler LoadScripts>>@@}}}
<<<
!!!!!Creating dynamic tiddler content and accessing the ~TiddlyWiki DOM
<<<
An important difference between TiddlyWiki inline 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()}}} (or {{{document.writeln()}}}) 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 instead will //completely replace the entire ~TiddlyWiki document in your browser window (which is clearly not a good thing!)//. In order to allow scripts to use {{{document.write()}}}, the plugin automatically converts and buffers all HTML output so it can be safely inserted into your tiddler content, immediately following the script.
''Note that {{{document.write()}}} can only be used to output "pure HTML" syntax. To produce //wiki-formatted// output, your script should instead return a text value containing the desired wiki-syntax content'', which will then be automatically rendered immediately following the script. If returning a text value is not sufficient for your needs, the plugin also provides an automatically-defined variable, 'place', that gives the script code ''direct access to the //containing DOM element//'' into which the tiddler output is being rendered. You can use this variable to ''perform direct DOM manipulations'' that can, for example:
* generate wiki-formatted output using {{{wikify("...content...",place)}}}
* vary the script's actions based upon the DOM element in which it is embedded
* access 'tiddler-relative' DOM information using {{{story.findContainingTiddler(place)}}}
Note:
''When using an 'onclick' script, the 'place' element actually refers to the onclick //link text// itself, instead of the containing DOM element.'' This permits you to directly reference or modify the link text to reflect any 'stateful' conditions that might set by the script. To refer to the containing DOM element from within an 'onclick' script, you can use "place.parentNode" instead.
<<<
!!!!!Instant "bookmarklets"
<<<
You can also use an 'onclick' link to define a "bookmarklet": a small piece of javascript that can be ''invoked directly from the browser without having to be defined within the current document.'' This allows you to create 'stand-alone' commands that can be applied to virtually ANY TiddlyWiki document... even remotely-hosted documents that have been written by others!! To create a bookmarklet, simply define an 'onclick' script and then grab the resulting link text and drag-and-drop it onto your browser's toolbar (or right-click and use the 'bookmark this link' command to add it to the browser's menu).
Notes:
*When writing scripts intended for use as bookmarklets, due to the ~URI-encoding required by the browser, ''you cannot not use ANY double-quotes (") within the bookmarklet script code.''
*All comments embedded in the bookmarklet script must ''use the fully-delimited {{{/* ... */}}} comment syntax,'' rather than the shorter {{{//}}} comment syntax.
*Most importantly, because bookmarklets are invoked directly from the browser interface and are not embedded within the TiddlyWiki document, there is NO containing 'place' DOM element surrounding the script. As a result, ''you cannot use a bookmarklet to generate dynamic output in your document,'' and using {{{document.write()}}} or returning wiki-syntax text or making reference to the 'place' DOM element will halt the script and report a "Reference Error" when that bookmarklet is invoked.
Please see [[InstantBookmarklets]] for many examples of 'onclick' scripts that can also be used as bookmarklets.
<<<
!!!!!Special reserved function name
<<<
The plugin 'wraps' all inline javascript code 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.
<<<
!!!!!$(...) 'shorthand' function
<<<
As described by Dustin Diaz [[here|http://www.dustindiaz.com/top-ten-javascript/]], the plugin defines a 'shorthand' function that allows you to write:
{{{
$(id)
}}}
in place of the normal standard javascript syntax:
{{{
document.getElementById(id)
}}}
This function is provided merely as a convenience for javascript coders that may be familiar with this abbreviation, in order to allow them to save a few bytes when writing their own inline script code.
<<<
!!!!!Examples
<<<
simple dynamic output:
><script show>
document.write("The current date/time is: "+(new Date())+"<br>");
return "link to current user: [["+config.options.txtUserName+"]]\n";
</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).getAttribute("tiddler");
var size=store.getTiddlerText(title).length;
return title+" is using "+size+" bytes";
</script>
dynamic output from an 'onclick' script, using {{{document.write()}}} and/or {{{return "..."}}}
><script label="click here" show>
document.write("<br>The current date/time is: "+(new Date())+"<br>");
return "link to current user: [["+config.options.txtUserName+"]]\n";
</script>
creating an 'onclick' button/link that accesses the link text AND the containing tiddler:
><script label="click here" title="clicking this link will show an 'alert' box" key="H" show>
if (!window.story) window.story=window;
var txt=place.firstChild.data;
var tid=story.findContainingTiddler(place).getAttribute('tiddler');
alert('Hello World!\nlinktext='+txt+'\ntiddler='+tid);
</script>
dynamically setting onclick link text based on stateful information:
>{{block{
{{{
<script label="click here">
/* toggle "txtSomething" value */
var on=(config.txtSomething=="ON");
place.innerHTML=on?"enable":"disable";
config.txtSomething=on?"OFF":"ON";
return "\nThe current value is: "+config.txtSomething;
</script><script>
/* initialize onclick link text based on current "txtSomething" value */
var on=(config.txtSomething=="ON");
place.lastChild.previousSibling.innerHTML=on?"disable":"enable";
</script>
}}}
<script label="click here">
/* toggle "txtSomething" value */
var on=(config.txtSomething=="ON");
place.innerHTML=on?"enable":"disable";
config.txtSomething=on?"OFF":"ON";
return "\nThe current value is: "+config.txtSomething;
</script><script>
/* initialize onclick link text based on current "txtSomething" value */
var on=(config.txtSomething=="ON");
place.lastChild.innerHTML=on?"enable":"disable";
</script>
}}}
loading a script from a source url:
>http://www.TiddlyTools.com/demo.js contains:
>>{{{function inlineJavascriptDemo() { alert('Hello from demo.js!!') } }}}
>>{{{displayMessage('InlineJavascriptPlugin: demo.js has been loaded');}}}
>note: When using this example on your local system, you will need to download the external script file from the above URL and install it into the same directory as your document.
>
><script src="demo.js" show>
return "inlineJavascriptDemo() function has been defined"
</script>
><script label="click to invoke inlineJavascriptDemo()" key="D" show>
inlineJavascriptDemo();
</script>
<<<
!!!!!Revisions
<<<
2008.06.11 [1.9.3] added $(...) function as 'shorthand' convenience syntax for document.getElementById()
2008.03.03 [1.9.2] corrected declaration of wikifyPlainText() for 'TW 2.1.x compatibility fallback' (fixes Safari "parse error")
2008.02.23 [1.9.1] in onclick function, use string instead of array for 'bufferedHTML' attribute on link element (fixes IE errors)
2008.02.21 [1.9.0] 'onclick' scripts now allow returned text (or document.write() calls) to be wikified into a span that immediately follows the onclick link. Also, added default 'return false' handling if no return value provided (prevents HREF from being triggered -- return TRUE to allow HREF to be processed). Thanks to Xavier Verges for suggestion and preliminary code.
2008.02.14 [1.8.1] added backward-compatibility for use of wikifyPlainText() in TW2.1.3 and earlier
2008.01.08 [*.*.*] plugin size reduction: documentation moved to ...Info tiddler
2007.12.28 [1.8.0] added support for key="X" syntax to specify custom access key definitions
2007.12.15 [1.7.0] autogenerate URI encoded HREF on links for onclick scripts. Drag links to browser toolbar to create bookmarklets. IMPORTANT NOTE: place is NOT defined when scripts are used as bookmarklets. In addition, double-quotes will cause syntax errors. Thanks to PaulReiber for debugging and brainstorming.
2007.11.26 [1.6.2] when converting "document.write()" function calls in inline code, allow whitespace between "write" and "(" so that "document.write ( foobar )" is properly converted.
2007.11.16 [1.6.1] when rendering "onclick scripts", pass label text through wikifyPlainText() to parse any embedded wiki-syntax to enable use of HTML entities or even TW macros to generate dynamic label text.
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
<<<
/%
|Name|InstantBookmarklets|
|Source|http://www.TiddlyTools.com/#InstantBookmarklets|
|Version|2.0.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|script|
|Requires|InlineJavascriptPlugin|
|Overrides||
|Description|instantly create bookmarklets by dragging onclick links to the browser toolbar|
See [[InlineJavascriptPluginInfo]] for bookmarklet authoring documentation
%/{{nowrap{
__[[InstantBookmarklets:|InstantBookmarklets]]__{{fine{__// drag these links to your browser toolbar!//__ <script label="(help...)">
alert("To create a bookmarklet, simply drag-and-drop any command link below directly onto your browser's toolbar or right-click and use 'bookmark this link' (or 'add to favorites') to add the bookmarklet to your browser's bookmarks menu. Once installed, you can use the bookmarklet with ANY TiddlyWiki document, even if the command script (and InlineJavascriptPlugin) has not been installed in that document!");
</script>}}}
//~TiddlyWiklets: {{fine{(TiddlyWiki "tear-off" utilities)}}}///%
========================== TOGGLE SITE TITLES %/
*<script label="▲ - Toggle site titles" title="show/hide SiteTitle and SiteSubtitle (header) content">
var c=document.getElementById('contentWrapper'); if (!c) return;
for (var i=0; i<c.childNodes.length; i++)
if (hasClass(c.childNodes[i],'header')) { var h=c.childNodes[i]; break; }
if (!h) return;
config.options.chkHideSiteTitles=h.style.display!='none';
h.style.display=config.options.chkHideSiteTitles?'none':'block';
saveOptionCookie('chkHideSiteTitles');
return false;
</script>/%
========================== TOGGLE LEFT SIDEBAR %/
*<<tiddler ToggleLeftSidebar with: "◄ - Toggle left sidebar">>/%
========================== TOGGLE RIGHT SIDEBAR %/
*<<tiddler ToggleRightSidebar with: "► - Toggle right sidebar">>/%
========================== TOGGLE ANIMATION EFFECTS %/
*<<tiddler ToggleAnimations with: "∞ - Toggle animation effects">>/%
========================== TOGGLE SINGLE PAGE MODE %/
*<<tiddler ToggleSinglePageMode with: "1 - Toggle single-page mode">>/%
========================== TOGGLE "FULLSCREEN" (SIDEBARS AND TITLES) %/
*<<tiddler ToggleFullScreen with: "◊ - Toggle fullscreen">>/%
========================== TOGGLE TIDDLER TITLES (and SUBTITLES) %/
*<<tiddler ToggleTiddlerTitles with: "T - Toggle tiddler titles">>/%
========================== TOGGLE TIDDLER TAGS %/
*<<tiddler ToggleTiddlerTags with: "# - Toggle tiddler tags">>/%
========================== RESTART WITHOUT RELOADING %/
*<script label="⌂ - Home" title="Restart initial page content WITHOUT RELOADING!">
story.closeAllTiddlers(); restart(); refreshPageTemplate();
return false;
</script>/%
========================== REFRESH WITHOUT RESTARTING %/
*<<tiddler RefreshPageDisplay with: "≈ - Refresh current display">>/%
========================== SHOW CURRENT VERSION, TIMESTAMP, and TIDDLER INFO %/
*<<tiddler ShowDocumentInfo>>/%
========================== RESET TIDDLYWIKI OPTION COOKIES (WITH CONFIRM) %/
*<<tiddler ResetOptionCookies>>/%
========================== CLEAR CHANGE COUNTERS %/
*<<tiddler ResetChangeCounters>>/%
========================== RESCUE STORE AREA (adapted from http://www.TiddlyWiki.com/#TiddlyBookmarklets) %/
*<<tiddler RescueStoreAreaCommand with: "∑ - Rescue current storeArea contents">>/%
========================== LOAD REMOTE PLUGINS... %/
//Load remote plugins: {{fine{(load on demand)}}}///%
========================== TiddlyTools (Eric Shulman)...%/
*[[TiddlyTools|http://www.TiddlyTools.com/]]{{block{/%
========================== LOAD IMPORT TIDDLERS PLUGIN
%/<<tiddler LoadRemotePlugin with:
[[ImportTiddlersPlugin]]
[[Load ImportTiddlersPlugin from svn.TiddlyWiki.org repository]]
[[http://svn.tiddlywiki.org/Trunk/contributors/EricShulman/plugins/ImportTiddlersPlugin.js]]
[[window.story.displayTiddler(null,'ImportTiddlers')]]
[[version.extensions.importTiddlers!=undefined]]
>>/%
========================== LOAD TIDDLER TWEAKER PLUGIN
%/<<tiddler LoadRemotePlugin with:
[[TiddlerTweakerPlugin]]
[[Load TiddlerTweakerPlugin from svn.TiddlyWiki.org repository]]
[[http://svn.tiddlywiki.org/Trunk/contributors/EricShulman/plugins/TiddlerTweakerPlugin.js]]
[[window.story.displayTiddler(null,'TiddlerTweaker')]]
[[version.extensions.tiddlerTweaker!=undefined]]
>>/%
========================== LOAD REARRANGE TIDDLERS PLUGIN
%/<<tiddler LoadRemotePlugin with:
[[RearrangeTiddlersPlugin]]
[[Load RearrangeTiddlersPlugin from www.TiddlyTools.com]]
[[http://www.TiddlyTools.com/plugins/RearrangeTiddlersPlugin.js]]
[[window.story.forEachTiddler(function(t,e){window.story.refreshTiddler(t,null,true)}); window.refreshDisplay()]]
[[Story.prototype.rearrangeTiddlersHijack_refreshTiddler!=undefined]]
>>/%
%/}}}/%
========================== Abego Software (Udo Borkowski)...%/
*[[Abego Software|http://tiddlywiki.abego-software.de/]]{{block{/%
========================== LOAD YOURSEARCH PLUGIN
%/<<tiddler LoadRemotePlugin with:
[[YourSearchPlugin]]
[[Load YourSearchPlugin from tiddlywiki.abego-software.de]]
[[http://tiddlywiki.abego-software.de/archive/YourSearchPlugin/Plugin-YourSearch-src.2.1.1.js]]
[[window.refreshPageTemplate()]]
[[version.extensions.YourSearchPlugin!=undefined]]
>>/%
%/}}}/%
========================== Firefox Privileges (Xavier Vergés) %/
*[[FirefoxPrivileges.TiddlySpot.com|http://firefoxprivileges.tiddlyspot.com/]]{{block{/%
========================== LOAD AND DISPLAY FIREFOX PRIVILEGE MANAGER
%/<<tiddler LoadRemotePlugin with:
[[Firefox Privilege Manager]]
[[Load Firefox Privilege Manager from svn.TiddlyWiki.org repository]]
[[http://svn.tiddlywiki.org/Trunk/contributors/XavierVerges/plugins/FirefoxPrivilegesPlugin.js]]
[[config.macros.firefoxPrivileges.onload()]]
[[config.macros.firefoxPrivileges!=undefined]]
[[backstage.switchTab("firefoxPrivileges")]]
>>/%
%/}}}/%
========================== Jash (Billy Reisinger) %/
*[[BillyReisinger.com:|http://www.billyreisinger.com/jash/]]{{block{/%
========================== LOAD AND DISPLAY JAVASCRIPT SHELL
%/<<tiddler LoadRemotePlugin with:
[[Jash (JAvascript SHell)]]
[[Load Jash (JAvascript SHell) from www.billyreisinger.com/jash]]
[[http://www.billyreisinger.com/jash/source/latest/Jash.js]]
[[window.jash.close()]]
[[window.jash!=undefined]]
>>/%
%/}}}
}}}/% END NOWRAP %/
/***
|Name:|InstantTimestampPlugin|
|Description:|A handy way to insert timestamps in your tiddler content|
|Version:|1.0.10 ($Rev: 3646 $)|
|Date:|$Date: 2008-02-27 02:34:38 +1000 (Wed, 27 Feb 2008) $|
|Source:|http://mptw.tiddlyspot.com/#InstantTimestampPlugin|
|Author:|Simon Baird <simon.baird@gmail.com>|
|License:|http://mptw.tiddlyspot.com/#TheBSDLicense|
!!Usage
If you enter {ts} in your tiddler content (without the spaces) it will be replaced with a timestamp when you save the tiddler. Full list of formats:
* {ts} or {t} -> timestamp
* {ds} or {d} -> datestamp
* !ts or !t at start of line -> !!timestamp
* !ds or !d at start of line -> !!datestamp
(I added the extra ! since that's how I like it. Remove it from translations below if required)
!!Notes
* Change the timeFormat and dateFormat below to suit your preference.
* See also http://mptw2.tiddlyspot.com/#AutoCorrectPlugin
* You could invent other translations and add them to the translations array below.
***/
//{{{
config.InstantTimestamp = {
// adjust to suit
timeFormat: 'DD/0MM/YY 0hh:0mm',
dateFormat: 'DD/0MM/YY',
translations: [
[/^!ts?$/img, "'!!{{ts{'+now.formatString(config.InstantTimestamp.timeFormat)+'}}}'"],
[/^!ds?$/img, "'!!{{ds{'+now.formatString(config.InstantTimestamp.dateFormat)+'}}}'"],
// thanks Adapted Cat
[/\{ts?\}(?!\}\})/ig,"'{{ts{'+now.formatString(config.InstantTimestamp.timeFormat)+'}}}'"],
[/\{ds?\}(?!\}\})/ig,"'{{ds{'+now.formatString(config.InstantTimestamp.dateFormat)+'}}}'"]
],
excludeTags: [
"noAutoCorrect",
"noTimestamp",
"html",
"CSS",
"css",
"systemConfig",
"systemConfigDisabled",
"zsystemConfig",
"Plugins",
"Plugin",
"plugins",
"plugin",
"javascript",
"code",
"systemTheme",
"systemPalette"
],
excludeTiddlers: [
"StyleSheet",
"StyleSheetLayout",
"StyleSheetColors",
"StyleSheetPrint"
// more?
]
};
TiddlyWiki.prototype.saveTiddler_mptw_instanttimestamp = TiddlyWiki.prototype.saveTiddler;
TiddlyWiki.prototype.saveTiddler = function(title,newTitle,newBody,modifier,modified,tags,fields,clearChangeCount,created) {
tags = tags ? tags : []; // just in case tags is null
tags = (typeof(tags) == "string") ? tags.readBracketedList() : tags;
var conf = config.InstantTimestamp;
if ( !tags.containsAny(conf.excludeTags) && !conf.excludeTiddlers.contains(newTitle) ) {
var now = new Date();
var trans = conf.translations;
for (var i=0;i<trans.length;i++) {
newBody = newBody.replace(trans[i][0], eval(trans[i][1]));
}
}
// TODO: use apply() instead of naming all args?
return this.saveTiddler_mptw_instanttimestamp(title,newTitle,newBody,modifier,modified,tags,fields,clearChangeCount,created);
}
// you can override these in StyleSheet
setStylesheet(".ts,.ds { font-style:italic; }","instantTimestampStyles");
//}}}
! CT200 - Fundamentos de Automata e Linguagens Formais
Prof. Carlos H. Q. Forster
<script>
document.write("forster"); document.write("@"); document.write("ita.br");
</script>
Ramal: 5981 Sala: 121
!AULA 2
* [[Propriedades de Relações]]
* [[Cardinalidade de Conjuntos Infinitos]]
* [[Estruturas de dados]]
* [[Tipos de Demonstração]]
* [[Linguagens]]
* [[Especificações finitas de linguagens]]
<<tiddler NextTiddler with: [[Propriedades de Relações]]>>
/***
|Name:|LessBackupsPlugin|
|Description:|Intelligently limit the number of backup files you create|
|Version:|3.0.1 ($Rev: 2320 $)|
|Date:|$Date: 2007-06-18 22:37:46 +1000 (Mon, 18 Jun 2007) $|
|Source:|http://mptw.tiddlyspot.com/#LessBackupsPlugin|
|Author:|Simon Baird|
|Email:|simon.baird@gmail.com|
|License:|http://mptw.tiddlyspot.com/#TheBSDLicense|
!!Description
You end up with just backup one per year, per month, per weekday, per hour, minute, and second. So total number won't exceed about 200 or so. Can be reduced by commenting out the seconds/minutes/hours line from modes array
!!Notes
Works in IE and Firefox only. Algorithm by Daniel Baird. IE specific code by by Saq Imtiaz.
***/
//{{{
var MINS = 60 * 1000;
var HOURS = 60 * MINS;
var DAYS = 24 * HOURS;
if (!config.lessBackups) {
config.lessBackups = {
// comment out the ones you don't want or set config.lessBackups.modes in your 'tweaks' plugin
modes: [
["YYYY", 365*DAYS], // one per year for ever
["MMM", 31*DAYS], // one per month
["ddd", 7*DAYS], // one per weekday
//["d0DD", 1*DAYS], // one per day of month
["h0hh", 24*HOURS], // one per hour
["m0mm", 1*HOURS], // one per minute
["s0ss", 1*MINS], // one per second
["latest",0] // always keep last version. (leave this).
]
};
}
window.getSpecialBackupPath = function(backupPath) {
var now = new Date();
var modes = config.lessBackups.modes;
for (var i=0;i<modes.length;i++) {
// the filename we will try
var specialBackupPath = backupPath.replace(/(\.)([0-9]+\.[0-9]+)(\.html)$/,
'$1'+now.formatString(modes[i][0]).toLowerCase()+'$3')
// open the file
try {
if (config.browser.isIE) {
var fsobject = new ActiveXObject("Scripting.FileSystemObject")
var fileExists = fsobject.FileExists(specialBackupPath);
if (fileExists) {
var fileObject = fsobject.GetFile(specialBackupPath);
var modDate = new Date(fileObject.DateLastModified).valueOf();
}
}
else {
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
file.initWithPath(specialBackupPath);
var fileExists = file.exists();
if (fileExists) {
var modDate = file.lastModifiedTime;
}
}
}
catch(e) {
// give up
return backupPath;
}
// expiry is used to tell if it's an 'old' one. Eg, if the month is June and there is a
// June file on disk that's more than an month old then it must be stale so overwrite
// note that "latest" should be always written because the expiration period is zero (see above)
var expiry = new Date(modDate + modes[i][1]);
if (!fileExists || now > expiry)
return specialBackupPath;
}
}
// hijack the core function
window.getBackupPath_mptw_orig = window.getBackupPath;
window.getBackupPath = function(localPath) {
return getSpecialBackupPath(getBackupPath_mptw_orig(localPath));
}
//}}}
!Cadeias de Símbolos e Linguagens
Strings, cadeias ou fitas: são seqüências finitas de símbolos.
Símbolos são entidades primitivas.
Alfabeto é um conjunto de símbolos
$Sigma_1={0,1}$
$Sigma_2={a,b,c,d,e,...,z}$
Uma string de um alfabeto $Sigma$ é uma seqüência finita de símbolos do alfabeto $Sigma$.
01001 é um cadeia do alfabeto $Sigma={0,1}$
Se $tt w$ é uma cadeia o comprimento de $tt w$ é escrito $|tt w|$ e é o número de símbolos que $ tt w$ contém.
A cadeia vazia tem tamanho zero e é escrita $epsilon$ ou $lambda$.
Substring $ttz$ de $ttw$ se $ttz$ aparece de forma consecutiva dentro de $ttw$.
cad é substring de abracadabra.
$ttw=w_1w_2w_3...w_n, w_i in Sigma$
Concatenação de $ttx=x_1x_2...x_n$ e $tty=y_1y_2...y_m$ é
$ttx tty = x_1 x_2 ... x_n y_1 y_2 ... y_m$
Concatenação múltipla de $ttx$ com si próprio
$ttx^k=x x x...x$ k vezes.
Ordem lexicográfica:
"ordem do dicionário", strings mais curtas precedem strings mais longas
$(epsilon, 0, 1, 00, 01, 10, 11, 000, ...)$
!Linguagens
Linguagem é o conjunto de strings sobre um alfabeto
$ emptyset$ é uma linguagem
${epsilon}$ é uma linguagem
> Qual a diferença entre as duas?
O conjunto dos palíndromos no alfabeto {0,1} é uma linguagem
${epsilon, 0, 1, 00, 11, 000, 101, 010, 111, ...}$
O conjunto de todas as strings sobre o alfabeto $Sigma$ é designada por $Sigma ^**$.
Para $Sigma={a}, Sigma^**={epsilon, a, aa, aaa, ...}$
Para $Sigma={0,1}, Sigma^**=?$
!!Definição
i) $epsilon in Sigma^**$
ii) Se $ttw in Sigma^**$ e $a in Sigma$, então $ttw a in Sigma^**$
iii) $w in Sigma^**$ apenas se puder ser obtida por um número finito de aplicações de (ii) a partir de $epsilon$.
Uma linguagem L sobre $Sigma$ é um subconjunto de $Sigma^**$.
!Concatenação de Strings
Sejam $ttu$ e $ttv in Sigma^**$. A concatenação $ttu ttv$ é uma operação binária definida em $Sigma^**$ da seguinte forma.
i) Se $|ttv|=0 => ttu ttv = ttu$
ii) Seja $ttv$ de comprimento n > 0. $ttv = ttw a$, onde $ttw$ é string de tamnho n-1 e $a in Sigma$, e $ttu ttv =(ttu ttw) a$
Concatenação é associativa, com elemento neutro $epsilon$.
!Reverso
$ ttu^R=(u_nu_(n-1)...u_1)$ onde $ttu=(u_1u_2...u_n)$
Definição recursiva:
i) Se $|ttu|=0 => ttu^R=epsilon$
ii) Se $|ttu|=n>0$, então $ttu=ttw a$ para alguma string $ttw, |ttw|=n-1$ e $a in Sigma$ e $ttu^R=attw^R$.
Propriedade: $(ttu ttv)^R=ttv ^R ttu^R$
>Demonstração:
> Base da Indução
> $|ttv|=0 => ttv=epsilon, (ttu ttv)^R=ttu^R$
> Analogamente, $ttv^R ttu^R=epsilon ttu^R =ttu^R
>
> Passo indutivo:
> $|ttv|=n+1$, provar $(ttu ttv)^R=ttv ^R ttu^R$
> $ttv=ttw a, |ttw|=n " e " a in Sigma$
> $(ttu ttv)^R = (ttu (ttw a) )^R = ( (ttu ttw)a)^R = a (ttu ttw)^R = a(ttw^R ttu^R) = (a ttw^R)ttu^R = (ttw a)^R ttu^R = ttv ^R ttu^R$.
>
>
<<tiddler NextTiddler with: [[Especificações finitas de linguagens]] >>
<script>
wikify("Toolbar commands are:\n",place);
for(var t in config.commands)
wikify("* "+t+"\n",place);
</script>
MPTW is a distribution or edition of TiddlyWiki that includes a standard TiddlyWiki core packaged with some plugins designed to improve usability and provide a better way to organise your information. For more information see http://mptw.tiddlyspot.com/.
[[Início]]
<<toggleSideBar "sidebar">>
<<fontSize>>
<<tiddler DigitalClock with: "0hh:0mm" 60>>
[[Agradecimentos]]
/***
|Name:|MathifyPlugin|
|Description:|Includes ASCIIMathML in your tiddlers with a plugin|
|Version:|1.0 ($Rev: 0000 $)|
|Date:|$Date: 2008-07-05$|
|Source:|to be announced|
|Author:|Mathifier|
|License:|GPL|
***/
//{{{
/* This is ASCIIMathML code copied and pasted. */
/* You may put it in a separate file instead, */
/* but I prefer it this way. */
/*
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 Aug 14, 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.
*/
var checkForMathML = true; // check if browser can display MathML
var notifyIfNoMathML = true; // put note at top of page if no MathML capability
var mathcolor = "red"; // change it to "" (to inherit) or any other color
var mathfontfamily = "serif"; // change to "" to inherit (works in IE)
// or another family (e.g. "arial")
var displaystyle = true; // puts limits above and below large operators
var showasciiformulaonhover = true; // helps students learn ASCIIMath
var decimalsign = "."; // change to "," if you like, beware of `(1,2)`!
var AMdelimiter1 = "`", AMescape1 = "\\\\`"; // can use other characters
var AMdelimiter2 = "$", AMescape2 = "\\\\\\$", AMdelimiter2regexp = "\\$";
var doubleblankmathdelimiter = false; // if true, x+1 is equal to `x+1`
// for IE this works only in <!-- -->
//var separatetokens;// has been removed (email me if this is a problem)
var isIE = document.createElementNS==null;
if (document.getElementById==null)
alert("This webpage requires a recent browser such as\
\nMozilla/Netscape 7+ or Internet Explorer 6+MathPlayer")
// all further global variables start with "AM"
function AMcreateElementXHTML(t) {
if (isIE) return document.createElement(t);
else return document.createElementNS("http://www.w3.org/1999/xhtml",t);
}
function AMnoMathMLNote() {
var nd = AMcreateElementXHTML("h3");
nd.setAttribute("align","center")
nd.appendChild(AMcreateElementXHTML("p"));
nd.appendChild(document.createTextNode("To view the "));
var an = AMcreateElementXHTML("a");
an.appendChild(document.createTextNode("ASCIIMathML"));
an.setAttribute("href","http://www.chapman.edu/~jipsen/asciimath.html");
nd.appendChild(an);
nd.appendChild(document.createTextNode(" notation use Internet Explorer 6+"));
an = AMcreateElementXHTML("a");
an.appendChild(document.createTextNode("MathPlayer"));
an.setAttribute("href","http://www.dessci.com/en/products/mathplayer/download.htm");
nd.appendChild(an);
nd.appendChild(document.createTextNode(" or Netscape/Mozilla/Firefox"));
nd.appendChild(AMcreateElementXHTML("p"));
return nd;
}
function AMisMathMLavailable() {
if (navigator.appName.slice(0,8)=="Netscape")
if (navigator.appVersion.slice(0,1)>="5") return null;
else return AMnoMathMLNote();
else if (navigator.appName.slice(0,9)=="Microsoft")
try {
var ActiveX = new ActiveXObject("MathPlayer.Factory.1");
return null;
} catch (e) {
return AMnoMathMLNote();
}
else return AMnoMathMLNote();
}
// character lists for Mozilla/Netscape fonts
var 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];
var 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];
var 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];
var CONST = 0, UNARY = 1, BINARY = 2, INFIX = 3, LEFTBRACKET = 4,
RIGHTBRACKET = 5, SPACE = 6, UNDEROVER = 7, DEFINITION = 8,
LEFTRIGHT = 9, TEXT = 10; // token types
var AMsqrt = {input:"sqrt", tag:"msqrt", output:"sqrt", tex:null, ttype:UNARY},
AMroot = {input:"root", tag:"mroot", output:"root", tex:null, ttype:BINARY},
AMfrac = {input:"frac", tag:"mfrac", output:"/", tex:null, ttype:BINARY},
AMdiv = {input:"/", tag:"mfrac", output:"/", tex:null, ttype:INFIX},
AMover = {input:"stackrel", tag:"mover", output:"stackrel", tex:null, ttype:BINARY},
AMsub = {input:"_", tag:"msub", output:"_", tex:null, ttype:INFIX},
AMsup = {input:"^", tag:"msup", output:"^", tex:null, ttype:INFIX},
AMtext = {input:"text", tag:"mtext", output:"text", tex:null, ttype:TEXT},
AMmbox = {input:"mbox", tag:"mtext", output:"mbox", tex:null, ttype:TEXT},
AMquote = {input:"\"", tag:"mtext", output:"mbox", tex:null, ttype:TEXT};
var AMsymbols = [
//some greek symbols
{input:"alpha", tag:"mi", output:"\u03B1", tex:null, ttype:CONST},
{input:"beta", tag:"mi", output:"\u03B2", tex:null, ttype:CONST},
{input:"chi", tag:"mi", output:"\u03C7", tex:null, ttype:CONST},
{input:"delta", tag:"mi", output:"\u03B4", tex:null, ttype:CONST},
{input:"Delta", tag:"mo", output:"\u0394", tex:null, ttype:CONST},
{input:"epsi", tag:"mi", output:"\u03B5", tex:"epsilon", ttype:CONST},
{input:"varepsilon", tag:"mi", output:"\u025B", tex:null, ttype:CONST},
{input:"eta", tag:"mi", output:"\u03B7", tex:null, ttype:CONST},
{input:"gamma", tag:"mi", output:"\u03B3", tex:null, ttype:CONST},
{input:"Gamma", tag:"mo", output:"\u0393", tex:null, ttype:CONST},
{input:"iota", tag:"mi", output:"\u03B9", tex:null, ttype:CONST},
{input:"kappa", tag:"mi", output:"\u03BA", tex:null, ttype:CONST},
{input:"lambda", tag:"mi", output:"\u03BB", tex:null, ttype:CONST},
{input:"Lambda", tag:"mo", output:"\u039B", tex:null, ttype:CONST},
{input:"mu", tag:"mi", output:"\u03BC", tex:null, ttype:CONST},
{input:"nu", tag:"mi", output:"\u03BD", tex:null, ttype:CONST},
{input:"omega", tag:"mi", output:"\u03C9", tex:null, ttype:CONST},
{input:"Omega", tag:"mo", output:"\u03A9", tex:null, ttype:CONST},
{input:"phi", tag:"mi", output:"\u03C6", tex:null, ttype:CONST},
{input:"varphi", tag:"mi", output:"\u03D5", tex:null, ttype:CONST},
{input:"Phi", tag:"mo", output:"\u03A6", tex:null, ttype:CONST},
{input:"pi", tag:"mi", output:"\u03C0", tex:null, ttype:CONST},
{input:"Pi", tag:"mo", output:"\u03A0", tex:null, ttype:CONST},
{input:"psi", tag:"mi", output:"\u03C8", tex:null, ttype:CONST},
{input:"Psi", tag:"mi", output:"\u03A8", tex:null, ttype:CONST},
{input:"rho", tag:"mi", output:"\u03C1", tex:null, ttype:CONST},
{input:"sigma", tag:"mi", output:"\u03C3", tex:null, ttype:CONST},
{input:"Sigma", tag:"mo", output:"\u03A3", tex:null, ttype:CONST},
{input:"tau", tag:"mi", output:"\u03C4", tex:null, ttype:CONST},
{input:"theta", tag:"mi", output:"\u03B8", tex:null, ttype:CONST},
{input:"vartheta", tag:"mi", output:"\u03D1", tex:null, ttype:CONST},
{input:"Theta", tag:"mo", output:"\u0398", tex:null, ttype:CONST},
{input:"upsilon", tag:"mi", output:"\u03C5", tex:null, ttype:CONST},
{input:"xi", tag:"mi", output:"\u03BE", tex:null, ttype:CONST},
{input:"Xi", tag:"mo", output:"\u039E", tex:null, ttype:CONST},
{input:"zeta", tag:"mi", output:"\u03B6", tex:null, ttype:CONST},
//binary operation symbols
{input:"*", tag:"mo", output:"\u22C5", tex:"cdot", ttype:CONST},
{input:"**", tag:"mo", output:"\u22C6", tex:"star", ttype:CONST},
{input:"//", tag:"mo", output:"/", tex:null, ttype:CONST},
{input:"\\\\", tag:"mo", output:"\\", tex:"backslash", ttype:CONST},
{input:"setminus", tag:"mo", output:"\\", tex:null, ttype:CONST},
{input:"xx", tag:"mo", output:"\u00D7", tex:"times", ttype:CONST},
{input:"-:", tag:"mo", output:"\u00F7", tex:"divide", ttype:CONST},
{input:"@", tag:"mo", output:"\u2218", tex:"circ", ttype:CONST},
{input:"o+", tag:"mo", output:"\u2295", tex:"oplus", ttype:CONST},
{input:"ox", tag:"mo", output:"\u2297", tex:"otimes", ttype:CONST},
{input:"o.", tag:"mo", output:"\u2299", tex:"odot", ttype:CONST},
{input:"sum", tag:"mo", output:"\u2211", tex:null, ttype:UNDEROVER},
{input:"prod", tag:"mo", output:"\u220F", tex:null, ttype:UNDEROVER},
{input:"ww", tag:"mo", output:"\u2227", tex:"wedge", ttype:CONST},
{input:"www", tag:"mo", output:"\u22C0", tex:"bigwedge", ttype:UNDEROVER},
{input:"vv", tag:"mo", output:"\u2228", tex:"vee", ttype:CONST},
{input:"vvv", tag:"mo", output:"\u22C1", tex:"bigvee", ttype:UNDEROVER},
{input:"nn", tag:"mo", output:"\u2229", tex:"cap", ttype:CONST},
{input:"nnn", tag:"mo", output:"\u22C2", tex:"bigcap", ttype:UNDEROVER},
{input:"uu", tag:"mo", output:"\u222A", tex:"cup", ttype:CONST},
{input:"uuu", tag:"mo", output:"\u22C3", tex:"bigcup", ttype:UNDEROVER},
//binary relation symbols
{input:"!=", tag:"mo", output:"\u2260", tex:"ne", ttype:CONST},
{input:":=", tag:"mo", output:":=", tex:null, ttype:CONST},
{input:"lt", tag:"mo", output:"<", tex:null, ttype:CONST},
{input:"<=", tag:"mo", output:"\u2264", tex:"le", ttype:CONST},
{input:"lt=", tag:"mo", output:"\u2264", tex:"leq", ttype:CONST},
{input:">=", tag:"mo", output:"\u2265", tex:"ge", ttype:CONST},
{input:"geq", tag:"mo", output:"\u2265", tex:null, ttype:CONST},
{input:"-<", tag:"mo", output:"\u227A", tex:"prec", ttype:CONST},
{input:"-lt", tag:"mo", output:"\u227A", tex:null, ttype:CONST},
{input:">-", tag:"mo", output:"\u227B", tex:"succ", ttype:CONST},
{input:"in", tag:"mo", output:"\u2208", tex:null, ttype:CONST},
{input:"!in", tag:"mo", output:"\u2209", tex:"notin", ttype:CONST},
{input:"sub", tag:"mo", output:"\u2282", tex:"subset", ttype:CONST},
{input:"sup", tag:"mo", output:"\u2283", tex:"supset", ttype:CONST},
{input:"sube", tag:"mo", output:"\u2286", tex:"subseteq", ttype:CONST},
{input:"supe", tag:"mo", output:"\u2287", tex:"supseteq", ttype:CONST},
{input:"subne", tag:"mo", output:"\u228A", tex:"supsetneq", ttype:CONST},
{input:"nsub", tag:"mo", output:"\u2284", tex:"notsubset", ttype:CONST},
{input:"nsup", tag:"mo", output:"\u2285", tex:"notsupset", ttype:CONST},
{input:"-=", tag:"mo", output:"\u2261", tex:"equiv", ttype:CONST},
{input:"~=", tag:"mo", output:"\u2245", tex:"cong", ttype:CONST},
{input:"~~", tag:"mo", output:"\u2248", tex:"approx", ttype:CONST},
{input:"prop", tag:"mo", output:"\u221D", tex:"propto", ttype:CONST},
//logical symbols
{input:"and", tag:"mtext", output:"and", tex:null, ttype:SPACE},
{input:"or", tag:"mtext", output:"or", tex:null, ttype:SPACE},
{input:"not", tag:"mo", output:"\u00AC", tex:"neg", ttype:CONST},
{input:"=>", tag:"mo", output:"\u21D2", tex:"implies", ttype:CONST},
{input:"if", tag:"mo", output:"if", tex:null, ttype:SPACE},
{input:"<=>", tag:"mo", output:"\u21D4", tex:"iff", ttype:CONST},
{input:"AA", tag:"mo", output:"\u2200", tex:"forall", ttype:CONST},
{input:"EE", tag:"mo", output:"\u2203", tex:"exists", ttype:CONST},
{input:"_|_", tag:"mo", output:"\u22A5", tex:"bot", ttype:CONST},
{input:"TT", tag:"mo", output:"\u22A4", tex:"top", ttype:CONST},
{input:"|--", tag:"mo", output:"\u22A2", tex:"vdash", ttype:CONST},
{input:"|==", tag:"mo", output:"\u22A8", tex:"models", ttype:CONST},
{input:"~~=", tag:"mo", output:"\u2243", tex:"simeq", ttype:CONST},
//grouping brackets
{input:"(", tag:"mo", output:"(", tex:null, ttype:LEFTBRACKET},
{input:")", tag:"mo", output:")", tex:null, ttype:RIGHTBRACKET},
{input:"[", tag:"mo", output:"[", tex:null, ttype:LEFTBRACKET},
{input:"]", tag:"mo", output:"]", tex:null, ttype:RIGHTBRACKET},
{input:"{", tag:"mo", output:"{", tex:null, ttype:LEFTBRACKET},
{input:"}", tag:"mo", output:"}", tex:null, ttype:RIGHTBRACKET},
{input:"|", tag:"mo", output:"|", tex:null, ttype:LEFTRIGHT},
//{input:"||", tag:"mo", output:"||", tex:null, ttype:LEFTRIGHT},
{input:"(:", tag:"mo", output:"\u2329", tex:"langle", ttype:LEFTBRACKET},
{input:":)", tag:"mo", output:"\u232A", tex:"rangle", ttype:RIGHTBRACKET},
{input:"<<", tag:"mo", output:"\u2329", tex:null, ttype:LEFTBRACKET},
{input:">>", tag:"mo", output:"\u232A", tex:null, ttype:RIGHTBRACKET},
{input:"{:", tag:"mo", output:"{:", tex:null, ttype:LEFTBRACKET, invisible:true},
{input:":}", tag:"mo", output:":}", tex:null, ttype:RIGHTBRACKET, invisible:true},
//miscellaneous symbols
{input:"int", tag:"mo", output:"\u222B", tex:null, ttype:CONST},
{input:"dx", tag:"mi", output:"{:d x:}", tex:null, ttype:DEFINITION},
{input:"dy", tag:"mi", output:"{:d y:}", tex:null, ttype:DEFINITION},
{input:"dz", tag:"mi", output:"{:d z:}", tex:null, ttype:DEFINITION},
{input:"dt", tag:"mi", output:"{:d t:}", tex:null, ttype:DEFINITION},
{input:"oint", tag:"mo", output:"\u222E", tex:null, ttype:CONST},
{input:"del", tag:"mo", output:"\u2202", tex:"partial", ttype:CONST},
{input:"grad", tag:"mo", output:"\u2207", tex:"nabla", ttype:CONST},
{input:"+-", tag:"mo", output:"\u00B1", tex:"pm", ttype:CONST},
{input:"O/", tag:"mo", output:"\u2205", tex:"emptyset", ttype:CONST},
{input:"oo", tag:"mo", output:"\u221E", tex:"infty", ttype:CONST},
{input:"aleph", tag:"mo", output:"\u2135", tex:null, ttype:CONST},
{input:"...", tag:"mo", output:"...", tex:"ldots", ttype:CONST},
{input:":.", tag:"mo", output:"\u2234", tex:"therefore", ttype:CONST},
{input:"/_", tag:"mo", output:"\u2220", tex:"angle", ttype:CONST},
{input:"\\ ", tag:"mo", output:"\u00A0", tex:null, ttype:CONST},
{input:"quad", tag:"mo", output:"\u00A0\u00A0", tex:null, ttype:CONST},
{input:"qquad", tag:"mo", output:"\u00A0\u00A0\u00A0\u00A0", tex:null, ttype:CONST},
{input:"cdots", tag:"mo", output:"\u22EF", tex:null, ttype:CONST},
{input:"vdots", tag:"mo", output:"\u22EE", tex:null, ttype:CONST},
{input:"ddots", tag:"mo", output:"\u22F1", tex:null, ttype:CONST},
{input:"diamond", tag:"mo", output:"\u22C4", tex:null, ttype:CONST},
{input:"square", tag:"mo", output:"\u25A1", tex:null, ttype:CONST},
{input:"|__", tag:"mo", output:"\u230A", tex:"lfloor", ttype:CONST},
{input:"__|", tag:"mo", output:"\u230B", tex:"rfloor", ttype:CONST},
{input:"|~", tag:"mo", output:"\u2308", tex:"lceiling", ttype:CONST},
{input:"~|", tag:"mo", output:"\u2309", tex:"rceiling", ttype:CONST},
{input:"CC", tag:"mo", output:"\u2102", tex:null, ttype:CONST},
{input:"NN", tag:"mo", output:"\u2115", tex:null, ttype:CONST},
{input:"QQ", tag:"mo", output:"\u211A", tex:null, ttype:CONST},
{input:"RR", tag:"mo", output:"\u211D", tex:null, ttype:CONST},
{input:"ZZ", tag:"mo", output:"\u2124", tex:null, ttype:CONST},
{input:"f", tag:"mi", output:"f", tex:null, ttype:UNARY, func:true},
{input:"g", tag:"mi", output:"g", tex:null, ttype:UNARY, func:true},
//standard functions
{input:"lim", tag:"mo", output:"lim", tex:null, ttype:UNDEROVER},
{input:"Lim", tag:"mo", output:"Lim", tex:null, ttype:UNDEROVER},
{input:"sin", tag:"mo", output:"sin", tex:null, ttype:UNARY, func:true},
{input:"cos", tag:"mo", output:"cos", tex:null, ttype:UNARY, func:true},
{input:"tan", tag:"mo", output:"tan", tex:null, ttype:UNARY, func:true},
{input:"sinh", tag:"mo", output:"sinh", tex:null, ttype:UNARY, func:true},
{input:"cosh", tag:"mo", output:"cosh", tex:null, ttype:UNARY, func:true},
{input:"tanh", tag:"mo", output:"tanh", tex:null, ttype:UNARY, func:true},
{input:"cot", tag:"mo", output:"cot", tex:null, ttype:UNARY, func:true},
{input:"sec", tag:"mo", output:"sec", tex:null, ttype:UNARY, func:true},
{input:"csc", tag:"mo", output:"csc", tex:null, ttype:UNARY, func:true},
{input:"log", tag:"mo", output:"log", tex:null, ttype:UNARY, func:true},
{input:"ln", tag:"mo", output:"ln", tex:null, ttype:UNARY, func:true},
{input:"det", tag:"mo", output:"det", tex:null, ttype:UNARY, func:true},
{input:"dim", tag:"mo", output:"dim", tex:null, ttype:CONST},
{input:"mod", tag:"mo", output:"mod", tex:null, ttype:CONST},
{input:"gcd", tag:"mo", output:"gcd", tex:null, ttype:UNARY, func:true},
{input:"lcm", tag:"mo", output:"lcm", tex:null, ttype:UNARY, func:true},
{input:"lub", tag:"mo", output:"lub", tex:null, ttype:CONST},
{input:"glb", tag:"mo", output:"glb", tex:null, ttype:CONST},
{input:"min", tag:"mo", output:"min", tex:null, ttype:UNDEROVER},
{input:"max", tag:"mo", output:"max", tex:null, ttype:UNDEROVER},
//arrows
{input:"uarr", tag:"mo", output:"\u2191", tex:"uparrow", ttype:CONST},
{input:"darr", tag:"mo", output:"\u2193", tex:"downarrow", ttype:CONST},
{input:"rarr", tag:"mo", output:"\u2192", tex:"rightarrow", ttype:CONST},
{input:"->", tag:"mo", output:"\u2192", tex:"to", ttype:CONST},
{input:"|->", tag:"mo", output:"\u21A6", tex:"mapsto", ttype:CONST},
{input:"larr", tag:"mo", output:"\u2190", tex:"leftarrow", ttype:CONST},
{input:"harr", tag:"mo", output:"\u2194", tex:"leftrightarrow", ttype:CONST},
{input:"rArr", tag:"mo", output:"\u21D2", tex:"Rightarrow", ttype:CONST},
{input:"lArr", tag:"mo", output:"\u21D0", tex:"Leftarrow", ttype:CONST},
{input:"hArr", tag:"mo", output:"\u21D4", tex:"Leftrightarrow", ttype:CONST},
//commands with argument
AMsqrt, AMroot, AMfrac, AMdiv, AMover, AMsub, AMsup,
{input:"hat", tag:"mover", output:"\u005E", tex:null, ttype:UNARY, acc:true},
{input:"bar", tag:"mover", output:"\u00AF", tex:"overline", ttype:UNARY, acc:true},
{input:"vec", tag:"mover", output:"\u2192", tex:null, ttype:UNARY, acc:true},
{input:"dot", tag:"mover", output:".", tex:null, ttype:UNARY, acc:true},
{input:"ddot", tag:"mover", output:"..", tex:null, ttype:UNARY, acc:true},
{input:"ul", tag:"munder", output:"\u0332", tex:"underline", ttype:UNARY, acc:true},
AMtext, AMmbox, AMquote,
{input:"bb", tag:"mstyle", atname:"fontweight", atval:"bold", output:"bb", tex:null, ttype:UNARY},
{input:"mathbf", tag:"mstyle", atname:"fontweight", atval:"bold", output:"mathbf", tex:null, ttype:UNARY},
{input:"sf", tag:"mstyle", atname:"fontfamily", atval:"sans-serif", output:"sf", tex:null, ttype:UNARY},
{input:"mathsf", tag:"mstyle", atname:"fontfamily", atval:"sans-serif", output:"mathsf", tex:null, ttype:UNARY},
{input:"bbb", tag:"mstyle", atname:"mathvariant", atval:"double-struck", output:"bbb", tex:null, ttype:UNARY, codes:AMbbb},
{input:"mathbb", tag:"mstyle", atname:"mathvariant", atval:"double-struck", output:"mathbb", tex:null, ttype:UNARY, codes:AMbbb},
{input:"cc", tag:"mstyle", atname:"mathvariant", atval:"script", output:"cc", tex:null, ttype:UNARY, codes:AMcal},
{input:"mathcal", tag:"mstyle", atname:"mathvariant", atval:"script", output:"mathcal", tex:null, ttype:UNARY, codes:AMcal},
{input:"tt", tag:"mstyle", atname:"fontfamily", atval:"monospace", output:"tt", tex:null, ttype:UNARY},
{input:"mathtt", tag:"mstyle", atname:"fontfamily", atval:"monospace", output:"mathtt", tex:null, ttype:UNARY},
{input:"fr", tag:"mstyle", atname:"mathvariant", atval:"fraktur", output:"fr", tex:null, ttype:UNARY, codes:AMfrk},
{input:"mathfrak", tag:"mstyle", atname:"mathvariant", atval:"fraktur", output:"mathfrak", tex:null, ttype:UNARY, codes:AMfrk}
];
function compareNames(s1,s2) {
if (s1.input > s2.input) return 1
else return -1;
}
var AMnames = []; //list of input symbols
function AMinitSymbols() {
var texsymbols = [], i;
for (i=0; i<AMsymbols.length; i++)
if (AMsymbols[i].tex)
texsymbols[texsymbols.length] = {input:AMsymbols[i].tex,
tag:AMsymbols[i].tag, output:AMsymbols[i].output, ttype:AMsymbols[i].ttype};
AMsymbols = AMsymbols.concat(texsymbols);
AMsymbols.sort(compareNames);
for (i=0; i<AMsymbols.length; i++) AMnames[i] = AMsymbols[i].input;
}
var AMmathml = "http://www.w3.org/1998/Math/MathML";
function AMcreateElementMathML(t) {
if (isIE) return document.createElement("m:"+t);
else return document.createElementNS(AMmathml,t);
}
function AMcreateMmlNode(t,frag) {
// var node = AMcreateElementMathML(name);
if (isIE) var node = document.createElement("m:"+t);
else var node = document.createElementNS(AMmathml,t);
node.appendChild(frag);
return node;
}
function newcommand(oldstr,newstr) {
AMsymbols = AMsymbols.concat([{input:oldstr, tag:"mo", output:newstr,
tex:null, ttype:DEFINITION}]);
}
function AMremoveCharsAndBlanks(str,n) {
//remove n characters and any following blanks
var st;
if (str.charAt(n)=="\\" && str.charAt(n+1)!="\\" && str.charAt(n+1)!=" ")
st = str.slice(n+1);
else st = str.slice(n);
for (var i=0; i<st.length && st.charCodeAt(i)<=32; i=i+1);
return st.slice(i);
}
function AMposition(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
}
function AMgetSymbol(str) {
//return maximal initial substring of str that appears in names
//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 = AMposition(AMnames, st, j);
if (k<AMnames.length && str.slice(0,AMnames[k].length)==AMnames[k]){
match = AMnames[k];
mk = k;
i = match.length;
}
more = k<AMnames.length && str.slice(0,AMnames[k].length)>=AMnames[k];
}
AMpreviousSymbol=AMcurrentSymbol;
if (match!=""){
AMcurrentSymbol=AMsymbols[mk].ttype;
return AMsymbols[mk];
}
// if str[0] is a digit or - return maxsubstring of digits.digits
AMcurrentSymbol=CONST;
k = 1;
st = str.slice(0,1);
var integ = true;
while ("0"<=st && st<="9" && k<=str.length) {
st = str.slice(k,k+1);
k++;
}
if (st == decimalsign) {
st = str.slice(k,k+1);
if ("0"<=st && st<="9") {
integ = false;
k++;
while ("0"<=st && st<="9" && k<=str.length) {
st = str.slice(k,k+1);
k++;
}
}
}
if ((integ && k>1) || k>2) {
st = str.slice(0,k-1);
tagst = "mn";
} else {
k = 2;
st = str.slice(0,1); //take 1 character
tagst = (("A">st || st>"Z") && ("a">st || st>"z")?"mo":"mi");
}
if (st=="-" && AMpreviousSymbol==INFIX)
return {input:st, tag:tagst, output:st, ttype:UNARY, func:true};
return {input:st, tag:tagst, output:st, ttype:CONST};
}
function AMremoveBrackets(node) {
var st;
if (node.nodeName=="mrow") {
st = node.firstChild.firstChild.nodeValue;
if (st=="(" || st=="[" || st=="{") node.removeChild(node.firstChild);
}
if (node.nodeName=="mrow") {
st = node.lastChild.firstChild.nodeValue;
if (st==")" || st=="]" || st=="}") node.removeChild(node.lastChild);
}
}
/*Parsing ASCII math expressions with the following grammar
v ::= [A-Za-z] | greek letters | numbers | other constant symbols
u ::= sqrt | text | bb | other unary symbols for font commands
b ::= frac | root | stackrel binary symbols
l ::= ( | [ | { | (: | {: left brackets
r ::= ) | ] | } | :) | :} right brackets
S ::= v | lEr | uS | bSS Simple expression
I ::= S_S | S^S | S_S^S | S Intermediate expression
E ::= IE | I/I Expression
Each terminal symbol is translated into a corresponding mathml node.*/
var AMnestingDepth,AMpreviousSymbol,AMcurrentSymbol;
function AMparseSexpr(str) { //parses str and returns [node,tailstr]
var symbol, node, result, i, st,// rightvert = false,
newFrag = document.createDocumentFragment();
str = AMremoveCharsAndBlanks(str,0);
symbol = AMgetSymbol(str); //either a token or a bracket or empty
if (symbol == null || symbol.ttype == RIGHTBRACKET && AMnestingDepth > 0) {
return [null,str];
}
if (symbol.ttype == DEFINITION) {
str = symbol.output+AMremoveCharsAndBlanks(str,symbol.input.length);
symbol = AMgetSymbol(str);
}
switch (symbol.ttype) {
case UNDEROVER:
case CONST:
str = AMremoveCharsAndBlanks(str,symbol.input.length);
return [AMcreateMmlNode(symbol.tag, //its a constant
document.createTextNode(symbol.output)),str];
case LEFTBRACKET: //read (expr+)
AMnestingDepth++;
str = AMremoveCharsAndBlanks(str,symbol.input.length);
result = AMparseExpr(str,true);
AMnestingDepth--;
if (typeof symbol.invisible == "boolean" && symbol.invisible)
node = AMcreateMmlNode("mrow",result[0]);
else {
node = AMcreateMmlNode("mo",document.createTextNode(symbol.output));
node = AMcreateMmlNode("mrow",node);
node.appendChild(result[0]);
}
return [node,result[1]];
case TEXT:
if (symbol!=AMquote) str = AMremoveCharsAndBlanks(str,symbol.input.length);
if (str.charAt(0)=="{") i=str.indexOf("}");
else if (str.charAt(0)=="(") i=str.indexOf(")");
else if (str.charAt(0)=="[") i=str.indexOf("]");
else if (symbol==AMquote) i=str.slice(1).indexOf("\"")+1;
else i = 0;
if (i==-1) i = str.length;
st = str.slice(1,i);
if (st.charAt(0) == " ") {
node = AMcreateElementMathML("mspace");
node.setAttribute("width","1ex");
newFrag.appendChild(node);
}
newFrag.appendChild(
AMcreateMmlNode(symbol.tag,document.createTextNode(st)));
if (st.charAt(st.length-1) == " ") {
node = AMcreateElementMathML("mspace");
node.setAttribute("width","1ex");
newFrag.appendChild(node);
}
str = AMremoveCharsAndBlanks(str,i+1);
return [AMcreateMmlNode("mrow",newFrag),str];
case UNARY:
str = AMremoveCharsAndBlanks(str,symbol.input.length);
result = AMparseSexpr(str);
if (result[0]==null) return [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=="/" || st=="|") {
return [AMcreateMmlNode(symbol.tag,
document.createTextNode(symbol.output)),str];
} else {
node = AMcreateMmlNode("mrow",
AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output)));
node.appendChild(result[0]);
return [node,result[1]];
}
}
AMremoveBrackets(result[0]);
if (symbol.input == "sqrt") { // sqrt
return [AMcreateMmlNode(symbol.tag,result[0]),result[1]];
} else if (typeof symbol.acc == "boolean" && symbol.acc) { // accent
node = AMcreateMmlNode(symbol.tag,result[0]);
node.appendChild(AMcreateMmlNode("mo",document.createTextNode(symbol.output)));
return [node,result[1]];
} else { // font change command
if (!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]=AMcreateElementMathML("mo").
appendChild(document.createTextNode(newst));
else result[0].replaceChild(AMcreateElementMathML("mo").
appendChild(document.createTextNode(newst)),result[0].childNodes[i]);
}
}
node = AMcreateMmlNode(symbol.tag,result[0]);
node.setAttribute(symbol.atname,symbol.atval);
return [node,result[1]];
}
case BINARY:
str = AMremoveCharsAndBlanks(str,symbol.input.length);
result = AMparseSexpr(str);
if (result[0]==null) return [AMcreateMmlNode("mo",
document.createTextNode(symbol.input)),str];
AMremoveBrackets(result[0]);
var result2 = AMparseSexpr(result[1]);
if (result2[0]==null) return [AMcreateMmlNode("mo",
document.createTextNode(symbol.input)),str];
AMremoveBrackets(result2[0]);
if (symbol.input=="root" || symbol.input=="stackrel")
newFrag.appendChild(result2[0]);
newFrag.appendChild(result[0]);
if (symbol.input=="frac") newFrag.appendChild(result2[0]);
return [AMcreateMmlNode(symbol.tag,newFrag),result2[1]];
case INFIX:
str = AMremoveCharsAndBlanks(str,symbol.input.length);
return [AMcreateMmlNode("mo",document.createTextNode(symbol.output)),str];
case SPACE:
str = AMremoveCharsAndBlanks(str,symbol.input.length);
node = AMcreateElementMathML("mspace");
node.setAttribute("width","1ex");
newFrag.appendChild(node);
newFrag.appendChild(
AMcreateMmlNode(symbol.tag,document.createTextNode(symbol.output)));
node = AMcreateElementMathML("mspace");
node.setAttribute("width","1ex");
newFrag.appendChild(node);
return [AMcreateMmlNode("mrow",newFrag),str];
case LEFTRIGHT:
// if (rightvert) return [null,str]; else rightvert = true;
AMnestingDepth++;
str = AMremoveCharsAndBlanks(str,symbol.input.length);
result = AMparseExpr(str,false);
AMnestingDepth--;
var st = "";
if (result[0].lastChild!=null)
st = result[0].lastChild.firstChild.nodeValue;
//alert(result[0].lastChild+"***"+st);
if (st == "|") { // its an absolute value subterm
node = AMcreateMmlNode("mo",document.createTextNode(symbol.output));
node = AMcreateMmlNode("mrow",node);
node.appendChild(result[0]);
return [node,result[1]];
} else { // the "|" is a \mid
node = AMcreateMmlNode("mo",document.createTextNode(symbol.output));
node = AMcreateMmlNode("mrow",node);
return [node,str];
}
default:
//alert("default");
str = AMremoveCharsAndBlanks(str,symbol.input.length);
return [AMcreateMmlNode(symbol.tag, //its a constant
document.createTextNode(symbol.output)),str];
}
}
function AMparseIexpr(str) {
var symbol, sym1, sym2, node, result, underover;
str = AMremoveCharsAndBlanks(str,0);
sym1 = AMgetSymbol(str);
result = AMparseSexpr(str);
node = result[0];
str = result[1];
symbol = AMgetSymbol(str);
if (symbol.ttype == INFIX && symbol.input != "/") {
str = AMremoveCharsAndBlanks(str,symbol.input.length);
// if (symbol.input == "/") result = AMparseIexpr(str); else ...
result = AMparseSexpr(str);
if (result[0] == null) // show box in place of missing argument
result[0] = AMcreateMmlNode("mo",document.createTextNode("\u25A1"));
else AMremoveBrackets(result[0]);
str = result[1];
// if (symbol.input == "/") AMremoveBrackets(node);
if (symbol.input == "_") {
sym2 = AMgetSymbol(str);
underover = (sym1.ttype == UNDEROVER);
if (sym2.input == "^") {
str = AMremoveCharsAndBlanks(str,sym2.input.length);
var res2 = AMparseSexpr(str);
AMremoveBrackets(res2[0]);
str = res2[1];
node = AMcreateMmlNode((underover?"munderover":"msubsup"),node);
node.appendChild(result[0]);
node.appendChild(res2[0]);
node = AMcreateMmlNode("mrow",node); // so sum does not stretch
} else {
node = AMcreateMmlNode((underover?"munder":"msub"),node);
node.appendChild(result[0]);
}
} else {
node = AMcreateMmlNode(symbol.tag,node);
node.appendChild(result[0]);
}
}
return [node,str];
}
function AMparseExpr(str,rightbracket) {
var symbol, node, result, i, nodeList = [],
newFrag = document.createDocumentFragment();
do {
str = AMremoveCharsAndBlanks(str,0);
result = AMparseIexpr(str);
node = result[0];
str = result[1];
symbol = AMgetSymbol(str);
if (symbol.ttype == INFIX && symbol.input == "/") {
str = AMremoveCharsAndBlanks(str,symbol.input.length);
result = AMparseIexpr(str);
if (result[0] == null) // show box in place of missing argument
result[0] = AMcreateMmlNode("mo",document.createTextNode("\u25A1"));
else AMremoveBrackets(result[0]);
str = result[1];
AMremoveBrackets(node);
node = AMcreateMmlNode(symbol.tag,node);
node.appendChild(result[0]);
newFrag.appendChild(node);
symbol = AMgetSymbol(str);
}
else if (node!=undefined) newFrag.appendChild(node);
} while ((symbol.ttype != RIGHTBRACKET &&
(symbol.ttype != LEFTRIGHT || rightbracket)
|| AMnestingDepth == 0) && symbol!=null && symbol.output!="");
if (symbol.ttype == RIGHTBRACKET || symbol.ttype == LEFTRIGHT) {
// if (AMnestingDepth > 0) AMnestingDepth--;
var len = newFrag.childNodes.length;
if (len>0 && newFrag.childNodes[len-1].nodeName == "mrow" && len>1 &&
newFrag.childNodes[len-2].nodeName == "mo" &&
newFrag.childNodes[len-2].firstChild.nodeValue == ",") { //matrix
var right = newFrag.childNodes[len-1].lastChild.firstChild.nodeValue;
if (right==")" || right=="]") {
var left = newFrag.childNodes[len-1].firstChild.firstChild.nodeValue;
if (left=="(" && right==")" && symbol.output != "}" ||
left=="[" && right=="]") {
var pos = []; // positions of commas
var matrix = true;
var m = newFrag.childNodes.length;
for (i=0; matrix && i<m; i=i+2) {
pos[i] = [];
node = newFrag.childNodes[i];
if (matrix) matrix = node.nodeName=="mrow" &&
(i==m-1 || node.nextSibling.nodeName=="mo" &&
node.nextSibling.firstChild.nodeValue==",")&&
node.firstChild.firstChild.nodeValue==left &&
node.lastChild.firstChild.nodeValue==right;
if (matrix)
for (var j=0; j<node.childNodes.length; j++)
if (node.childNodes[j].firstChild.nodeValue==",")
pos[i][pos[i].length]=j;
if (matrix && i>1) matrix = pos[i].length == pos[i-2].length;
}
if (matrix) {
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;
node.removeChild(node.firstChild); //remove (
for (j=1; j<n-1; j++) {
if (typeof pos[i][k] != "undefined" && j==pos[i][k]){
node.removeChild(node.firstChild); //remove ,
row.appendChild(AMcreateMmlNode("mtd",frag));
k++;
} else frag.appendChild(node.firstChild);
}
row.appendChild(AMcreateMmlNode("mtd",frag));
if (newFrag.childNodes.length>2) {
newFrag.removeChild(newFrag.firstChild); //remove <mrow>)</mrow>
newFrag.removeChild(newFrag.firstChild); //remove <mo>,</mo>
}
table.appendChild(AMcreateMmlNode("mtr",row));
}
node = AMcreateMmlNode("mtable",table);
if (typeof symbol.invisible == "boolean" && symbol.invisible) node.setAttribute("columnalign","left");
newFrag.replaceChild(node,newFrag.firstChild);
}
}
}
}
str = AMremoveCharsAndBlanks(str,symbol.input.length);
if (typeof symbol.invisible != "boolean" || !symbol.invisible) {
node = AMcreateMmlNode("mo",document.createTextNode(symbol.output));
newFrag.appendChild(node);
}
}
return [newFrag,str];
}
function AMparseMath(str) {
var result, node = AMcreateElementMathML("mstyle");
if (mathcolor != "") node.setAttribute("mathcolor",mathcolor);
if (displaystyle) node.setAttribute("displaystyle","true");
if (mathfontfamily != "") node.setAttribute("fontfamily",mathfontfamily);
AMnestingDepth = 0;
node.appendChild(AMparseExpr(str.replace(/^\s+/g,""),false)[0]);
node = AMcreateMmlNode("math",node);
if (showasciiformulaonhover) //fixed by djhsu so newline
node.setAttribute("title",str.replace(/\s+/g," "));//does not show in Gecko
if (mathfontfamily != "" && (isIE || mathfontfamily != "serif")) {
var fnode = AMcreateElementXHTML("font");
fnode.setAttribute("face",mathfontfamily);
fnode.appendChild(node);
return fnode;
}
return node;
}
function AMstrarr2docFrag(arr, linebreaks) {
var newFrag=document.createDocumentFragment();
var expr = false;
for (var i=0; i<arr.length; i++) {
if (expr) newFrag.appendChild(AMparseMath(arr[i]));
else {
var arri = (linebreaks ? arr[i].split("\n\n") : [arr[i]]);
newFrag.appendChild(AMcreateElementXHTML("span").
appendChild(document.createTextNode(arri[0])));
for (var j=1; j<arri.length; j++) {
newFrag.appendChild(AMcreateElementXHTML("p"));
newFrag.appendChild(AMcreateElementXHTML("span").
appendChild(document.createTextNode(arri[j])));
}
}
expr = !expr;
}
return newFrag;
}
function AMprocessNodeR(n, linebreaks) {
var mtch, str, arr, frg, i;
if (n.childNodes.length == 0) {
if ((n.nodeType!=8 || linebreaks) &&
n.parentNode.nodeName!="form" && n.parentNode.nodeName!="FORM" &&
n.parentNode.nodeName!="textarea" && n.parentNode.nodeName!="TEXTAREA" &&
n.parentNode.nodeName!="pre" && n.parentNode.nodeName!="PRE") {
str = n.nodeValue;
if (!(str == null)) {
str = str.replace(/\r\n\r\n/g,"\n\n");
if (doubleblankmathdelimiter) {
str = str.replace(/\x20\x20\./g," "+AMdelimiter1+".");
str = str.replace(/\x20\x20,/g," "+AMdelimiter1+",");
str = str.replace(/\x20\x20/g," "+AMdelimiter1+" ");
}
str = str.replace(/\x20+/g," ");
str = str.replace(/\s*\r\n/g," ");
mtch = false;
str = str.replace(new RegExp(AMescape2, "g"),
function(st){mtch=true;return "AMescape2"});
str = str.replace(new RegExp(AMescape1, "g"),
function(st){mtch=true;return "AMescape1"});
str = str.replace(new RegExp(AMdelimiter2regexp, "g"),AMdelimiter1);
arr = str.split(AMdelimiter1);
for (i=0; i<arr.length; i++)
arr[i]=arr[i].replace(/AMescape2/g,AMdelimiter2).
replace(/AMescape1/g,AMdelimiter1);
if (arr.length>1 || mtch) {
if (checkForMathML) {
checkForMathML = false;
var nd = AMisMathMLavailable();
AMnoMathML = nd != null
if (AMnoMathML && notifyIfNoMathML)
AMbody.insertBefore(nd,AMbody.childNodes[0]);
}
if (!AMnoMathML) {
frg = AMstrarr2docFrag(arr,n.nodeType==8);
var len = frg.childNodes.length;
n.parentNode.replaceChild(frg,n);
return len-1;
} else return 0;
}
}
} else return 0;
} else if (n.nodeName!="math") {
for (i=0; i<n.childNodes.length; i++)
i += AMprocessNodeR(n.childNodes[i], linebreaks);
}
return 0;
}
function AMprocessNode(n, linebreaks, spanclassAM) {
var frag,st;
if (spanclassAM!=null) {
frag = document.getElementsByTagName("span")
for (var i=0;i<frag.length;i++)
if (frag[i].className == "AM")
AMprocessNodeR(frag[i],linebreaks);
} else {
try {
st = n.innerHTML;
} catch(err) {}
if (st==null ||
st.indexOf(AMdelimiter1)!=-1 || st.indexOf(AMdelimiter2)!=-1)
AMprocessNodeR(n,linebreaks);
}
if (isIE) { //needed to match size and font of formula to surrounding text
frag = document.getElementsByTagName('math');
for (var i=0;i<frag.length;i++) frag[i].update()
}
}
var AMbody;
var AMnoMathML = false, AMtranslated = false;
AMinitSymbols(); // moved out of translate for TiddlyWiki
function translate(spanclassAM) {
//if (!AMtranslated)
{ // run this only once
AMtranslated = true;
AMbody = document.getElementsByTagName("body")[0];
AMprocessNode(AMbody, false, spanclassAM);
}
}
/************* my code goes here *********************/
Story.prototype.OLDMrefreshTiddler=Story.prototype.refreshTiddler;
Story.prototype.refreshTiddler=function(title,template,force,customFields,defaultText)
{
var k=this.OLDMrefreshTiddler(title, template, force,
customFields,defaultText);
AMprocessNode(k,false);
return k;
}
//}}}
/%
|Name|MicroCalc|
|Source|http://www.TiddlyTools.com/#MicroCalc|
|Version|1.1.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|html|
|Requires||
|Overrides||
|Description|a simple embeddable calculator using javascript eval() function|
Usage: <<tiddler MicroCalc>>
%/<<tiddler HideTiddlerTags>>/%
%/{{small smallform{/%
%/<html><div style="width:100%"><hide linebreaks>
<form action="javascript:;" style="display:inline;margin:0;padding:0;"><!--
--><input name="input" value="0" style="width:70%;text-align:right;"
title="INPUT: enter a JavaScript expression, function, or object/variable name"
onfocus="this.select()"
onkeyup="if (event.keyCode==13) {this.form.go.click(); return false;}"><!--
--><input name="go" type="button" value="=" style="width:5%"
title="CALCULATE: evaluate input and display results"
onclick="var i=this.form.input; var o=this.form.output; var val=i.value; var res='';
try{res=eval(val);i.value=res}catch(e){res=e.description||e.toString()};
o.value+=(o.value.length?'\n':'')+val+'\n='+res;
o.style.display='block'; o.scrollTop=o.scrollHeight;
i.select();i.focus();"><!--
--><input name="memstore" type="button" value="m" style="width:5%"
title="MEMORY STORE: save input to temporary memory"
onclick="var f=this.form; f.memory.value=f.input.value;
f.memory.parentNode.style.display='block'"><!--
--><input name="clear" type="button" value="c" style="width:5%"
title="CLEAR: erase history and reset input"
onclick="var i=this.form.input; var o=this.form.output;
o.value='';o.style.display='none';
i.value='0';i.select();i.focus();"><!--
--><div style="display:none"><!--
--><input name="memory" value="0" style="width:70%;text-align:right;"
title="MEMORY: temporarily store input during calculations"><!--
--><input name="meminsert" type="button" value="mi" style="width:5%"
title="MEMORY INSERT: append memory value to current input"
onclick="var i=this.form.input;
i.value+=this.form.memory.value; i.select();i.focus();"><!--
--><input name="memrecall" type="button" value="mr" style="width:5%"
title="MEMORY RECALL: replace current input with memory value "
onclick="var i=this.form.input;
i.value=this.form.memory.value; i.select();i.focus();"><!--
--><input name="memclear" type="button" value="mc" style="width:5%"
title="MEMORY CLEAR: clear temporary memory"
onclick="var f=this.form; f.memory.value='0';
f.memory.parentNode.style.display='none';
f.input.select();f.input.focus();"><!--
--></div><!--
--><textarea name="output" rows=5 style="width:99%;display:none;"
title="HISTORY: previous inputs and calculated results"></textarea><!--
--></form></div></html>/%
%/}}}
/%
|Name|MoveTiddlerToTop|
|Source|http://www.TiddlyTools.com/#MoveTiddlerToTop|
|Version|1.0.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|script|
|Requires||
|Overrides||
|Description|reposition the current tiddler to top of the story column|
Usage: <<tiddler MoveTiddlerToTop>>
%/<script>
var here=story.findContainingTiddler(place); if (!here) return;
here.parentNode.insertBefore(here,here.parentNode.firstChild); // move to top of column
</script>
Name: MptwBlack
Background: #000
Foreground: #fff
PrimaryPale: #333
PrimaryLight: #555
PrimaryMid: #888
PrimaryDark: #aaa
SecondaryPale: #111
SecondaryLight: #222
SecondaryMid: #555
SecondaryDark: #888
TertiaryPale: #222
TertiaryLight: #666
TertiaryMid: #888
TertiaryDark: #aaa
Error: #300
This is in progress. Help appreciated.
Name: MptwBlue
Background: #fff
Foreground: #000
PrimaryPale: #cdf
PrimaryLight: #57c
PrimaryMid: #114
PrimaryDark: #012
SecondaryPale: #ffc
SecondaryLight: #fe8
SecondaryMid: #db4
SecondaryDark: #841
TertiaryPale: #eee
TertiaryLight: #ccc
TertiaryMid: #999
TertiaryDark: #666
Error: #f88
/***
|Name:|MptwConfigPlugin|
|Description:|Miscellaneous tweaks used by MPTW|
|Version:|1.0 ($Rev: 3646 $)|
|Date:|$Date: 2008-02-27 02:34:38 +1000 (Wed, 27 Feb 2008) $|
|Source:|http://mptw.tiddlyspot.com/#MptwConfigPlugin|
|Author:|Simon Baird <simon.baird@gmail.com>|
|License:|http://mptw.tiddlyspot.com/#MptwConfigPlugin|
!!Note: instead of editing this you should put overrides in MptwUserConfigPlugin
***/
//{{{
var originalReadOnly = readOnly;
var originalShowBackstage = showBackstage;
config.options.chkHttpReadOnly = false; // means web visitors can experiment with your site by clicking edit
readOnly = false; // needed because the above doesn't work any more post 2.1 (??)
showBackstage = true; // show backstage for same reason
config.options.chkInsertTabs = true; // tab inserts a tab when editing a tiddler
config.views.wikified.defaultText = ""; // don't need message when a tiddler doesn't exist
config.views.editor.defaultText = ""; // don't need message when creating a new tiddler
config.options.chkSaveBackups = true; // do save backups
config.options.txtBackupFolder = 'twbackup'; // put backups in a backups folder
config.options.chkAutoSave = (window.location.protocol == "file:"); // do autosave if we're in local file
config.mptwVersion = "2.4.5";
config.macros.mptwVersion={handler:function(place){wikify(config.mptwVersion,place);}};
if (config.options.txtTheme == '')
config.options.txtTheme = 'MptwTheme';
// add to default GettingStarted
config.shadowTiddlers.GettingStarted += "\n\nSee also [[MPTW]].";
// add select theme and palette controls in default OptionsPanel
config.shadowTiddlers.OptionsPanel = config.shadowTiddlers.OptionsPanel.replace(/(\n\-\-\-\-\nAlso see AdvancedOptions)/, "{{select{<<selectTheme>>\n<<selectPalette>>}}}$1");
// these are used by ViewTemplate
config.mptwDateFormat = 'DD/MM/YY';
config.mptwJournalFormat = 'Journal DD/MM/YY';
//}}}
Name: MptwGreen
Background: #fff
Foreground: #000
PrimaryPale: #9b9
PrimaryLight: #385
PrimaryMid: #031
PrimaryDark: #020
SecondaryPale: #ffc
SecondaryLight: #fe8
SecondaryMid: #db4
SecondaryDark: #841
TertiaryPale: #eee
TertiaryLight: #ccc
TertiaryMid: #999
TertiaryDark: #666
Error: #f88
Name: MptwRed
Background: #fff
Foreground: #000
PrimaryPale: #eaa
PrimaryLight: #c55
PrimaryMid: #711
PrimaryDark: #500
SecondaryPale: #ffc
SecondaryLight: #fe8
SecondaryMid: #db4
SecondaryDark: #841
TertiaryPale: #eee
TertiaryLight: #ccc
TertiaryMid: #999
TertiaryDark: #666
Error: #f88
|Name|MptwRounded|
|Description|Mptw Theme with some rounded corners (Firefox only)|
|ViewTemplate|MptwTheme##ViewTemplate|
|EditTemplate|MptwTheme##EditTemplate|
|PageTemplate|MptwTheme##PageTemplate|
|StyleSheet|##StyleSheet|
!StyleSheet
/*{{{*/
[[MptwTheme##StyleSheet]]
.tiddler,
.sliderPanel,
.button,
.tiddlyLink,
.tabContents
{ -moz-border-radius: 1em; }
.tab {
-moz-border-radius-topleft: 0.5em;
-moz-border-radius-topright: 0.5em;
}
#topMenu {
-moz-border-radius-bottomleft: 2em;
-moz-border-radius-bottomright: 2em;
}
/*}}}*/
Name: MptwSmoke
Background: #fff
Foreground: #000
PrimaryPale: #aaa
PrimaryLight: #777
PrimaryMid: #111
PrimaryDark: #000
SecondaryPale: #ffc
SecondaryLight: #fe8
SecondaryMid: #db4
SecondaryDark: #841
TertiaryPale: #eee
TertiaryLight: #ccc
TertiaryMid: #999
TertiaryDark: #666
Error: #f88
|Name|MptwStandard|
|Description|Mptw Theme with the default TiddlyWiki PageLayout and Styles|
|ViewTemplate|MptwTheme##ViewTemplate|
|EditTemplate|MptwTheme##EditTemplate|
Name: MptwTeal
Background: #fff
Foreground: #000
PrimaryPale: #B5D1DF
PrimaryLight: #618FA9
PrimaryMid: #1a3844
PrimaryDark: #000
SecondaryPale: #ffc
SecondaryLight: #fe8
SecondaryMid: #db4
SecondaryDark: #841
TertiaryPale: #f8f8f8
TertiaryLight: #bbb
TertiaryMid: #999
TertiaryDark: #888
Error: #f88
|Name|MptwTheme|
|Description|Mptw Theme including custom PageLayout|
|PageTemplate|##PageTemplate|
|ViewTemplate|##ViewTemplate|
|EditTemplate|##EditTemplate|
|StyleSheet|##StyleSheet|
http://mptw.tiddlyspot.com/#MptwTheme ($Rev: 1829 $)
!PageTemplate
<!--{{{-->
<div class='header' macro='gradient vert [[ColorPalette::PrimaryLight]] [[ColorPalette::PrimaryMid]]'>
<div class='headerShadow'>
<span class='siteTitle' refresh='content' tiddler='SiteTitle'></span>
<span class='siteSubtitle' refresh='content' tiddler='SiteSubtitle'></span>
</div>
<div class='headerForeground'>
<span class='siteTitle' refresh='content' tiddler='SiteTitle'></span>
<span class='siteSubtitle' refresh='content' tiddler='SiteSubtitle'></span>
</div>
</div>
<!-- horizontal MainMenu -->
<div id='topMenu' refresh='content' tiddler='MainMenu'></div>
<!-- original MainMenu menu -->
<!-- <div id='mainMenu' refresh='content' tiddler='MainMenu'></div> -->
<div id='sidebar'>
<div id='sidebarOptions' refresh='content' tiddler='SideBarOptions'></div>
<div id='sidebarTabs' refresh='content' force='true' tiddler='SideBarTabs'></div>
</div>
<div id='displayArea'>
<div id='messageArea'></div>
<div id='tiddlerDisplay'></div>
</div>
<!--}}}-->
!ViewTemplate
<!--{{{-->
[[MptwTheme##ViewTemplateToolbar]]
<div class="tagglyTagged" macro="tags"></div>
<div class='titleContainer'>
<span class='title' macro='view title'></span>
<span macro="miniTag"></span>
</div>
<div class='subtitle'>
(updated <span macro='view modified date {{config.mptwDateFormat?config.mptwDateFormat:"MM/0DD/YY"}}'></span>
by <span macro='view modifier link'></span>)
<!--
(<span macro='message views.wikified.createdPrompt'></span>
<span macro='view created date {{config.mptwDateFormat?config.mptwDateFormat:"MM/0DD/YY"}}'></span>)
-->
</div>
<div macro="showWhen tiddler.tags.containsAny(['css','html','pre','systemConfig']) && !tiddler.text.match('{{'+'{')">
<div class='viewer'><pre macro='view text'></pre></div>
</div>
<div macro="else">
<div class='viewer' macro='view text wikified'></div>
</div>
<div class="tagglyTagging" macro="tagglyTagging"></div>
<!--}}}-->
!ViewTemplateToolbar
<!--{{{-->
<div class='toolbar'>
<span macro="showWhenTagged systemConfig">
<span macro="toggleTag systemConfigDisable . '[[disable|systemConfigDisable]]'"></span>
</span>
<span macro="showWhenTagged systemTheme"><span macro="applyTheme"></span></span>
<span macro="showWhenTagged systemPalette"><span macro="applyPalette"></span></span>
<span macro="showWhen tiddler.tags.contains('css') || tiddler.title == 'StyleSheet'"><span macro="refreshAll"></span></span>
<span style="padding:1em;"></span>
<span macro='toolbar closeTiddler closeOthers +editTiddler deleteTiddler > fields syncing permalink references jump'></span> <span macro='newHere label:"new here"'></span>
<span macro='newJournalHere {{config.mptwJournalFormat?config.mptwJournalFormat:"MM/0DD/YY"}}'></span>
</div>
<!--}}}-->
!EditTemplate
<!--{{{-->
<div class="toolbar" macro="toolbar +saveTiddler saveCloseTiddler closeOthers -cancelTiddler cancelCloseTiddler deleteTiddler"></div>
<div class="title" macro="view title"></div>
<div class="editLabel">Title</div><div class="editor" macro="edit title"></div>
<div macro='annotations'></div>
<div class="editLabel">Content</div><div class="editor" macro="edit text"></div>
<div class="editLabel">Tags</div><div class="editor" macro="edit tags"></div>
<div class="editorFooter"><span macro="message views.editor.tagPrompt"></span><span macro="tagChooser"></span></div>
<!--}}}-->
!StyleSheet
/*{{{*/
/* a contrasting background so I can see where one tiddler ends and the other begins */
body {
background: [[ColorPalette::TertiaryLight]];
}
/* sexy colours and font for the header */
.headerForeground {
color: [[ColorPalette::PrimaryPale]];
}
.headerShadow, .headerShadow a {
color: [[ColorPalette::PrimaryMid]];
}
/* separate the top menu parts */
.headerForeground, .headerShadow {
padding: 1em 1em 0;
}
.headerForeground, .headerShadow {
font-family: 'Trebuchet MS' sans-serif;
font-weight:bold;
}
.headerForeground .siteSubtitle {
color: [[ColorPalette::PrimaryLight]];
}
.headerShadow .siteSubtitle {
color: [[ColorPalette::PrimaryMid]];
}
/* make shadow go and down right instead of up and left */
.headerShadow {
left: 1px;
top: 1px;
}
/* prefer monospace for editing */
.editor textarea, .editor input {
font-family: 'Consolas' monospace;
background-color:[[ColorPalette::TertiaryPale]];
}
/* sexy tiddler titles */
.title {
font-size: 250%;
color: [[ColorPalette::PrimaryLight]];
font-family: 'Trebuchet MS' sans-serif;
}
/* more subtle tiddler subtitle */
.subtitle {
padding:0px;
margin:0px;
padding-left:1em;
font-size: 90%;
color: [[ColorPalette::TertiaryMid]];
}
.subtitle .tiddlyLink {
color: [[ColorPalette::TertiaryMid]];
}
/* a little bit of extra whitespace */
.viewer {
padding-bottom:3px;
}
/* don't want any background color for headings */
h1,h2,h3,h4,h5,h6 {
background-color: transparent;
color: [[ColorPalette::Foreground]];
}
/* give tiddlers 3d style border and explicit background */
.tiddler {
background: [[ColorPalette::Background]];
border-right: 2px [[ColorPalette::TertiaryMid]] solid;
border-bottom: 2px [[ColorPalette::TertiaryMid]] solid;
margin-bottom: 1em;
padding:1em 2em 2em 1.5em;
}
/* make options slider look nicer */
#sidebarOptions .sliderPanel {
border:solid 1px [[ColorPalette::PrimaryLight]];
}
/* the borders look wrong with the body background */
#sidebar .button {
border-style: none;
}
/* this means you can put line breaks in SidebarOptions for readability */
#sidebarOptions br {
display:none;
}
/* undo the above in OptionsPanel */
#sidebarOptions .sliderPanel br {
display:inline;
}
/* horizontal main menu stuff */
#displayArea {
margin: 1em 15.7em 0em 1em; /* use the freed up space */
}
#topMenu br {
display: none;
}
#topMenu {
background: [[ColorPalette::PrimaryMid]];
color:[[ColorPalette::PrimaryPale]];
}
#topMenu {
padding:2px;
}
#topMenu .button, #topMenu .tiddlyLink, #topMenu a {
margin-left: 0.5em;
margin-right: 0.5em;
padding-left: 3px;
padding-right: 3px;
color: [[ColorPalette::PrimaryPale]];
font-size: 115%;
}
#topMenu .button:hover, #topMenu .tiddlyLink:hover {
background: [[ColorPalette::PrimaryDark]];
}
/* make 2.2 act like 2.1 with the invisible buttons */
.toolbar {
visibility:hidden;
}
.selected .toolbar {
visibility:visible;
}
/* experimental. this is a little borked in IE7 with the button
* borders but worth it I think for the extra screen realestate */
.toolbar { float:right; }
/* fix for TaggerPlugin. from sb56637. improved by FND */
.popup li .tagger a {
display:inline;
}
/* makes theme selector look a little better */
#sidebarOptions .sliderPanel .select .button {
padding:0.5em;
display:block;
}
#sidebarOptions .sliderPanel .select br {
display:none;
}
/* make it print a little cleaner */
@media print {
#topMenu {
display: none ! important;
}
/* not sure if we need all the importants */
.tiddler {
border-style: none ! important;
margin:0px ! important;
padding:0px ! important;
padding-bottom:2em ! important;
}
.tagglyTagging .button, .tagglyTagging .hidebutton {
display: none ! important;
}
.headerShadow {
visibility: hidden ! important;
}
.tagglyTagged .quickopentag, .tagged .quickopentag {
border-style: none ! important;
}
.quickopentag a.button, .miniTag {
display: none ! important;
}
}
/* get user styles specified in StyleSheet */
[[StyleSheet]]
/*}}}*/
|Name|MptwTrim|
|Description|Mptw Theme with a reduced header to increase useful space|
|ViewTemplate|MptwTheme##ViewTemplate|
|EditTemplate|MptwTheme##EditTemplate|
|StyleSheet|MptwTheme##StyleSheet|
|PageTemplate|##PageTemplate|
!PageTemplate
<!--{{{-->
<!-- horizontal MainMenu -->
<div id='topMenu' macro='gradient vert [[ColorPalette::PrimaryLight]] [[ColorPalette::PrimaryMid]]'>
<span refresh='content' tiddler='SiteTitle' style="padding-left:1em;font-weight:bold;"></span>:
<span refresh='content' tiddler='MainMenu'></span>
</div>
<div id='sidebar'>
<div id='sidebarOptions'>
<div refresh='content' tiddler='SideBarOptions'></div>
<div style="margin-left:0.1em;"
macro='slider chkTabSliderPanel SideBarTabs {{"tabs \u00bb"}} "Show Timeline, All, Tags, etc"'></div>
</div>
</div>
<div id='displayArea'>
<div id='messageArea'></div>
<div id='tiddlerDisplay'></div>
</div>
For upgrading. See [[ImportTiddlers]].
URL: http://mptw.tiddlyspot.com/upgrade.html
/***
|Description:|A place to put your config tweaks so they aren't overwritten when you upgrade MPTW|
See http://www.tiddlywiki.org/wiki/Configuration_Options for other options you can set. In some cases where there are clashes with other plugins it might help to rename this to zzMptwUserConfigPlugin so it gets executed last.
***/
//{{{
// example: set your preferred date format
//config.mptwDateFormat = 'MM/0DD/YY';
//config.mptwJournalFormat = 'Journal MM/0DD/YY';
// example: set the theme you want to start with
//config.options.txtTheme = 'MptwRoundTheme';
// example: switch off autosave, switch on backups and set a backup folder
config.options.chkSaveBackups = false;
config.options.chkAutoSave = false;
config.options.txtBackupFolder = 'backups';
//}}}
config.commands.closeTiddler.imgLoc="data:image/gif;base64,R0lGODlhEAAQAMQfAOt0dP94eOFjY/a0tP/JyfFfX/yVlf6mppNtbf5qanknJ9dVVeZqat5eXpiMjGo4OIUvL3pGRthWVuhvb1kaGv39/f1lZdg7O/7Y2F8/P+13d4tcXNRTU2dCQv///////yH5BAEAAB8ALAAAAAAQABAAAAV/4Cd+Xml6Y0pGTosgEap6G0YQh6FDskhjGg0AMJkwAjxfBygkGhmCAAXl6QyGnuLFI4g+qNbixLMNdBNfkpXBLncbial6AC17Gvg4eND1BPB3cHJVBguGhwsSHHo+GRqKHJGRCQo9JI4WBZoFFpUVMw8QCqMQU58qJCclqKytIQA7";
config.commands.closeOthers.imgLoc="data:image/gif;base64,R0lGODlhEAAQAMQfAJLNW3aXtJnM/OTs9YivyMfj/ldwkabS+73d/UpXbdXb5PP2+dHn+uv1/uvx9mGNRIm77LXZ/H6xW1Jhe6/S5ERNX5rA1qjL3uLw/t7o8CkxQz9GVsvM0WOPRf///////yH5BAEAAB8ALAAAAAAQABAAAAWYoCeO5PidHkNRl2URRCAHHkplg6M7Qz9AhpqH4igYjYhkAwIUXRbHwuOhbCwmIgvU2JFIHpHwNbvtAM4A8GHsIUA78DO8s06I3IhGwyzpYDAHA3YeAQ1JCHwPBwcCAxUiAQ5JEXN0AgIZj4SSYQyeBZeYG5ALCGGLi6EOox4GCgs8PhmzDhwakAa5ExMJCRUVGxsaWCXFJSEAOw==";
config.commands.editTiddler.imgLoc="data:image/gif;base64,R0lGODlhEAAQAMQAAGB3lYivyMDf/XiZt+Ts9ajT/Mbh/UlVa/P2+bLY/FRlfu3x9ZzN++Xy/rTR4ENLXN7v/tTk8Jm/1enx96jL3uDo7ykxQz5FVb2JAP+8Bv/RV6HQ/FSr9qfR+jhllf///yH5BAAAAAAALAAAAAAQABAAAAWV4CeOZClGjkNJUhAMsOdJohMRUz4RvNdxntrEQCQKGj6gQkRBFAXHpAex/EicBijy54FQRddslAspfD8BhBZDLpgPovQRo8l0C50NAf4ZLBp0GRhleXoPIn4RdYN4GxsMFYd9CwkKlgoAAwybFReICAkJeAUDAKYAC54fABEIOzwEFbILDhaImJcHBw8PFxcWVSbCIiEAOw==";
config.commands.saveTiddler.imgLoc="data:image/gif;base64,R0lGODlhEAAQANUkAOLp8LHX/PH1+ENLXElVa5XK/JrA1j5FVYm77Lvc/a7T5bba/LDR49Xn8N7n74ivyKjL3ikxQ+nv9NXb5MvM0Z7O+1Jhe1dwkcDf/ezx9oXIWe3x9naXtKTR+/L2+uXt9avU+8fj/n2/Uv///////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAACQALAAAAAAQABAAAAaewJFwSBySjqOGggExGB4PjpQzQioan0xW++kiLtUR4xMqlzFoD+IrhHjMIYwgkfDYLULD+ywQSRYLAR54IwYjfCIaIhsBIINDIiNyiYuNjgRClH2KGyAgHR0fmJmKnJ6gFR8DQlSUnZ8dFRUAqyMcGRuVsBUFBQ4HrB4JjKeyvRnAIxcTHlwAzwAOGRQRrBfXFhYEBAMDBwcRhEXjREEAOw==";
config.commands.cancelTiddler.imgLoc="data:image/gif;base64,R0lGODlhEAAQANUiALba/OLp8ElVa0NLXIivyJXK/MDf/T5FVbvc/Ym77MvM0ZrA1t7n7ykxQ67T5dXn8LDR46jL3tXb5J7O+1Jhe1dwkbHX/KvU+6TR++zx9naXtMfj/u0xMeXt9fL2+u3x9s8dHf///////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAACIALAAAAAAQABAAAAaewJBwSByKjqGHAxJZLAgEjVQTQjoenUxW2+kmKtUQpLMplw1oT+IrjHg+5o8BgfDYKcLFBwTffxAAABYeeCEKIBx8iHyCF4RCBB6LiR8WFheOApBvi5WYGBgdmiEaGZN8F6ATHQNCh5SdGBMTAa2kfgB+sgUFDAdCGm+NH7ITvBm/IRUSHlwBzwEMGQoNwBXXFBQCAgMDBwcNhUXjREEAOw==";
config.commands.deleteTiddler.imgLoc="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAJ2SURBVBgZBcFLiJVlGADg5/3+b87cbLyFNBJ4oexGQYqIi6hFQambgohoE0aLUqGCaBcuonWLUFe1CIJolWCLaiK1C0FUREpRBgmWNpqi4XjOnP97e57ITI+8fuLZ6bnJZ0rYhikECGSQzbi1M1cu5UJcvfzqycN7RgCRmXa9+dXJ9w5su6uUWJV0EoBMSIv/LXv/uyvOnx1eP/3zL2u+PLxnCBVKF3cMarfq1D+6EkGQjT6b8TgtLfceuv0mO7ZU37bFmWx3Xn5w/7HVx9/ePSwQESsysxt0xUShBl2hCyIoAs383MCe7fM23jY5Xedm34UCSUBBCUqEEqFEKBFKF/7+d8mGFcvuXhOe37lWN9E9CRUgk9oRQkZofVJC7Rhk8fulNGpjrY08sHlS1DKGCpkkahQpJaKEQDayKwwoLbTWSYUooEKiIYIQEolsTHSAKKIPWVJDJlChjcmkIZCZoBS0ULskgySFvtE3oEJrKTNJUgKQQAj950eMFg5ZPvebU+vW2zH9WGWnCn2jT7LRACRoyY2FI6ZOfeC+p54zuekeSz99YubkQv304YkDFdo4tUwHfxgJqQWZQSMjPX30Lbv3vmDqzBeceMPMylU2b9jg+1/z5Qrjca/vmZ+bsHVd0ZI+6YOWrL7yp6lbNrHrFQD14LyuxcYK42Fr49Zy1ItvzvVapBSgJetXzrv+4zGzR180XDrvOq5d7fSdvyos3+gvzA66m1+7dzSbmUXSACunq4vn9zt9/B23rp5WuwnXFsf+uNBJ/aHITNv3fbZvvJyPR8T9KWcAJImUHh0eq1sXP+zWDi/G1cHc8Oxgy8cvffT1E/8D2iAtJW5RUGAAAAAASUVORK5CYII=";
config.commands.permalink.imgLoc="data:image/gif;base64,R0lGODlhEAAQAMQfAKxoR8VkLxFw1feVPITSWv+eQv7Qo0Cc6OyIN/v7+3PLTSCZEFy17Wa6XuT1x2bGQ3nNUU6vRXPAa9mLXMTkwJZEHJt7LL5aJ/z8/O2KONx3L/ubP/r6+rtVI////////yH5BAEAAB8ALAAAAAAQABAAAAWD4CeOZDlimOitnvlhXefFiyCs3NkZMe9QDMGik3t1BgZDIcZgHCCxHAyxKRQmnYOkoYgaNYMNr3JoEB6dDBGmyWxihwNBgVZz2Js3YB+JWNprHW15YgA2FxkaRB8JgoQxHQEbdiKNg4R5iYuVgpcZmkUjHDEapYqbJRyjkKouoqqhIyEAOw==";
config.commands.references.imgLoc="data:image/gif;base64,R0lGODlhEAAQANUrAJu81zqa6oyz2aPYioGt2VarVUunzme1jT6Miuf4yGag2XjJTm6wzNDpvK3W+Ze3y0qotz6CuTR7y4i213i6ii6WKNvo7bbW62Oa2pvK+oWy58jf8VSRuVCmTM7i9FSR2+Dt8o7Hjbrfuy53yIrKdz13uSVxxkSgOr7a9er0/////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAACsALAAAAAAQABAAAAaOQJVwSByujipOJFJqOpuq40oFSFmvV0IUCUB5v1/BdvpIKbDZseoBRl0oHQkGJKWaraJCQ7WZILZUXx5/CSQBBw0nUSoCdxoOCQMQBgskJIqMXxIOEwwBlAUDmAACBAQjFp6fBSeiRSohAyQHEAEmCAeKUkgnCQsVJiYZJmO7KieWDB/Eu83HwczNzkZSQQA7";
config.commands.jump.imgLoc="data:image/gif;base64,R0lGODlhEAAQAMQfAJLNW3aXtMfj/pfL/OTr9IivyMvM0Vdwkb7e/UpXbfP2+azU+9Xo9Ovx9u32/mGNRIm77OPx/rXZ/H6xW1Jhe6/S5ERNX5rA1qjL3tvj6ykxQz9GVqDP+2OPRf///////yH5BAEAAB8ALAAAAAAQABAAAAWYoCeO5PidHlNV2HUVRSAHHloxRKM3RE9Ah5qn0hAYjYikAwIUYRRHAaKjdCgoogv0OO1IvtfstkPuALyLsKcAnQLegEknnRCxk4/J5D15CAh1HgENSWVmDxEcBBYig0kMEREdiBwDi42EXwsLHYkDAxkbjQoImgsclZ8Noh4HGQo8Pj0ZDQYajQe5FBQJCRYWGxsaWCXFJSEAOw==";
config.commands.syncing.imgLoc="data:image/gif;base64,R0lGODlhEAAQAMQfAJXG2JXa+ZLO5ChrlkCy4TZ1kiVvpCN0trvo9SN5xTd4lrfh7iR9zo3S+EGz7JDJ4TaCromrvC9ymyV+0Dd3mTl1koe72YvN7LTj+9ne6N3g6v7+/0Cw2Stoh////////yH5BAEAAB8ALAAAAAAQABAAAAV94CeOXumJ5ah6VVFQpXSqX6YgC4JAljGTnYVAwCFcMIffx9OJdDqDB8HRSCiZCpMh0GgwroWTZ2A4JBiTn2nNVk8YiYNhIA6vGJhAwFdSdK4JAQ4EDwMDTX8rBwEXBBxDAIkrBhYQDw8AAAoaGzQeMh4ULhVKJDNrNKmqNCEAOw==";
config.commands.fields.imgLoc="data:image/gif;base64,R0lGODlhEAAQAMQAAHyqzUprjGiTtzpae4Gvz1V5nmaXyFyApG2cyom10oay0Uxvkk5yllR8o1yRxFGIwXelzY2t03KfwXekxZFggajA3uFCQsXa6VWDvUZmhfT1+NXZ4unr8P///wAAAAAAACH5BAAAAAAALAAAAAAQABAAAAVrYCeOZCleiQJACGJETvRQlZgSq2twDvdYGJtmSCwODyIFZ8lsLpEdAmez3Fiv1IJIap2WqAwRoIm9chZip5oTEE2m1TK13ZFMqZsvJyMSkOV7fWtOfB1QJiQDfQ0NBQUMCwEBGZQDioiYHSEAOw==";
/***
|Name:|NewHerePlugin|
|Description:|Creates the new here and new journal macros|
|Version:|3.0 ($Rev: 3861 $)|
|Date:|$Date: 2008-03-08 10:53:09 +1000 (Sat, 08 Mar 2008) $|
|Source:|http://mptw.tiddlyspot.com/#NewHerePlugin|
|Author:|Simon Baird <simon.baird@gmail.com>|
|License|http://mptw.tiddlyspot.com/#TheBSDLicense|
***/
//{{{
merge(config.macros, {
newHere: {
handler: function(place,macroName,params,wikifier,paramString,tiddler) {
wikify("<<newTiddler "+paramString+" tag:[["+tiddler.title+"]]>>",place,null,tiddler);
}
},
newJournalHere: {
handler: function(place,macroName,params,wikifier,paramString,tiddler) {
wikify("<<newJournal "+paramString+" tag:[["+tiddler.title+"]]>>",place,null,tiddler);
}
}
});
//}}}
/***
|Name:|NewMeansNewPlugin|
|Description:|If 'New Tiddler' already exists then create 'New Tiddler (1)' and so on|
|Version:|1.1 ($Rev: 2263 $)|
|Date:|$Date: 2007-06-13 04:22:32 +1000 (Wed, 13 Jun 2007) $|
|Source:|http://mptw.tiddlyspot.com/empty.html#NewMeansNewPlugin|
|Author:|Simon Baird <simon.baird@gmail.com>|
|License|http://mptw.tiddlyspot.com/#TheBSDLicense|
!!Note: I think this should be in the core
***/
//{{{
String.prototype.getNextFreeName = function() {
var numberRegExp = / \(([0-9]+)\)$/;
var match = numberRegExp.exec(this);
if (match) {
var num = parseInt(match[1]) + 1;
return this.replace(numberRegExp," ("+num+")");
}
else {
return this + " (1)";
}
}
config.macros.newTiddler.checkForUnsaved = function(newName) {
var r = false;
story.forEachTiddler(function(title,element) {
if (title == newName)
r = true;
});
return r;
}
config.macros.newTiddler.getName = function(newName) {
while (store.getTiddler(newName) || config.macros.newTiddler.checkForUnsaved(newName))
newName = newName.getNextFreeName();
return newName;
}
config.macros.newTiddler.onClickNewTiddler = function()
{
var title = this.getAttribute("newTitle");
if(this.getAttribute("isJournal") == "true") {
var now = new Date();
title = now.formatString(title.trim());
}
title = config.macros.newTiddler.getName(title); // <--- only changed bit
var params = this.getAttribute("params");
var tags = params ? params.split("|") : [];
var focus = this.getAttribute("newFocus");
var template = this.getAttribute("newTemplate");
var customFields = this.getAttribute("customFields");
story.displayTiddler(null,title,template,false,null,null);
var tiddlerElem = document.getElementById(story.idPrefix + title);
if(customFields)
story.addCustomFields(tiddlerElem,customFields);
var text = this.getAttribute("newText");
if(typeof text == "string")
story.getTiddlerField(title,"text").value = text.format([title]);
for(var t=0;t<tags.length;t++)
story.setTiddlerTag(title,tags[t],+1);
story.focusTiddler(title,focus);
return false;
};
//}}}
/%
|Name|NextTiddler|
|Source|http://www.TiddlyTools.com/#NextTiddler|
|Version|0.0.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|script|
|Requires|InlineJavascriptPlugin|
|Overrides||
|Description|insert a link that, when clicked, closes the current tiddler and opens another one in its place|
usage: <<tiddler NextTiddler with: NewTiddlerTitle linktext>>
%/<script label="próximo">
var tiddler=story.findContainingTiddler(place);
story.displayTiddler(tiddler,"$1");
story.closeTiddler(tiddler.getAttribute("tiddler")); // close self
return false;
</script>
<!--{{{-->
<!--{{{-->
<div macro='polyglot'></div> or <span macro='polyglot'></span>
<div class='header' macro='gradient vert [[ColorPalette::PrimaryLight]] [[ColorPalette::PrimaryMid]]'>
<div class='headerShadow'>
<span class='siteTitle' refresh='content' tiddler='SiteTitle'></span>
<span class='siteSubtitle' refresh='content' tiddler='SiteSubtitle'></span>
</div>
<div class='headerForeground'>
<span class='siteTitle' refresh='content' tiddler='SiteTitle'></span>
<span class='siteSubtitle' refresh='content' tiddler='SiteSubtitle'></span>
</div>
</div>
<div id='mainMenu' refresh='content' tiddler='MainMenu'></div>
<div id='sidebar'>
<div id='sidebarOptions' refresh='content' tiddler='SideBarOptions'></div>
<div id='sidebarTabs' refresh='content' force='true' tiddler='SideBarTabs'></div>
</div>
<div id='displayArea'>
<div id='messageArea'></div>
<div id='tiddlerDisplay'></div>
</div>
<!--}}}-->
<!--}}}-->
/***
|Name:|PrettyDatesPlugin|
|Description:|Provides a new date format ('pppp') that displays times such as '2 days ago'|
|Version:|1.0 ($Rev: 3646 $)|
|Date:|$Date: 2008-02-27 02:34:38 +1000 (Wed, 27 Feb 2008) $|
|Source:|http://mptw.tiddlyspot.com/#PrettyDatesPlugin|
|Author:|Simon Baird <simon.baird@gmail.com>|
|License:|http://mptw.tiddlyspot.com/#TheBSDLicense|
!!Notes
* If you want to you can rename this plugin. :) Some suggestions: LastUpdatedPlugin, RelativeDatesPlugin, SmartDatesPlugin, SexyDatesPlugin.
* Inspired by http://ejohn.org/files/pretty.js
***/
//{{{
Date.prototype.prettyDate = function() {
var diff = (((new Date()).getTime() - this.getTime()) / 1000);
var day_diff = Math.floor(diff / 86400);
if (isNaN(day_diff)) return "";
else if (diff < 0) return "in the future";
else if (diff < 60) return "just now";
else if (diff < 120) return "1 minute ago";
else if (diff < 3600) return Math.floor(diff/60) + " minutes ago";
else if (diff < 7200) return "1 hour ago";
else if (diff < 86400) return Math.floor(diff/3600) + " hours ago";
else if (day_diff == 1) return "Yesterday";
else if (day_diff < 7) return day_diff + " days ago";
else if (day_diff < 14) return "a week ago";
else if (day_diff < 31) return Math.ceil(day_diff/7) + " weeks ago";
else if (day_diff < 62) return "a month ago";
else if (day_diff < 365) return "about " + Math.ceil(day_diff/31) + " months ago";
else if (day_diff < 730) return "a year ago";
else return Math.ceil(day_diff/365) + " years ago";
}
Date.prototype.formatString_orig_mptw = Date.prototype.formatString;
Date.prototype.formatString = function(template) {
return this.formatString_orig_mptw(template).replace(/pppp/,this.prettyDate());
}
// for MPTW. otherwise edit your ViewTemplate as required.
// config.mptwDateFormat = 'pppp (DD/MM/YY)';
config.mptwDateFormat = 'pppp';
//}}}
!Partições
Seja A={1,2,3,...,10}
e os subconjuntos $B_1={1,3}, B_2={7,8,10}, B_3={2,5,6}, B_4={4,9}$
$tt B={B_1, B_2, B_3, B_4}$ família de conjuntos com as propriedades:
* $A= uuu_(B in tt B)B=uuu_(i=1)^4B_i=B_1 uu B_2 uu B_3 uu B_4$
* Para quaisquer conjuntos $B_i, B_j$ em $tt B$ com $ i neq j$:
$B_i nn B_j = emptyset$
$( AA B_i, b_j in tt B, B_i=B_j vv B_i nn B_j=emptyset)$
$tt B$ é então uma partição de A e cada $B_i$ é um bloco de A.
! Relação de Equivalência
A relação R em X é chamada uma relação de equivalência sse R for
1 - Reflexiva: $AA x in X, xRx$
2 - Simétrica: $ AA x,y in X, xRy -> yRx$
3 - Transitiva: $AA x,y,z in X, xRy " e " yRz -> xRz$
Se R é uma relação de equivalência, a classe de equivalência contendo x é:
$R[x]={y|y in X " e " xRy} $
Uma relação de equivalência em X particiona X em classes de equivalência disjuntas.
1 - Suponha que $x in R[y]$ e $x in R[z]$.
2 - Isso implica que $yRx$ e que $zRx$.
3 - Pela propriedade simétrica de R, temos que $xRz$.
4 - Pela propriedade transitiva de R, temos que $yRx, xRz -> yRz => y in R[z]$.
5 - Assim $R[y] sub R[z]$.
6 - De forma análoga, obtemos que $R[z] sub R[y]$.
7 - A partir de (5) e (6) conclui-se que $R[y]=R[z]$
8 - Pela propriedade reflexiva, $AA x, x in R[x]$, ou seja, a partição cobre todo o conjunto X.
O ranque de R é o número de classes de equivalência.
! Composição de relações
$R_1 sub X xx Z, R_2 sub Z xx Y$
$x(R_1 R_2)y <=> EE z in Z, x R_1 z " e " z R_2 y$
! Fechamento da composição de relações no caso de funções
$(x,z) in h <=> EE y in B | (x,y) in f " e " (y,z) in g$
f é função $A->B$
g é função $B->C$
Provar que h é função.
$h= f @ g : A -> C$
Equivale provar que
$(x,y) in h$ e $(x,z) in h -> y=z$
$(x,y) in h -> EE k in B | (x,k) in f " e " (k,y) in g$
$(x,z) in h -> EE l in B | (x,l) in f " e " (l,z) in g$
$(x,l) in f " e " (x,k) in f " e f é função " -> l=k$
$(k,y) in g " e " (l,z)=(k,z) in g " e g é função " -> y=z$
! Propriedades em potencial de relações
Para relações podem ou não ocorrer as seguintes propriedades:
# reflexiva: $AA x in S, xRx$
# antissimétrica: $ AA x,y in S, xRy ww yRx => x=y$
# transitiva: $ AA x,y,z in S, xRy ww yRz => xRz $
# comparabilidade: $ AA x,y in S, xRy vv yRx$
# simétrica:$AA x,y in S, xRy => yRx$
Para operações, as seguintes propriedades podem ou não ocorrer:
# associativa: $ AA x,y,z, in S, x @ (y @ z) = (x @ y) @ z$
# elemento neutro ou identidade: $ EE| e in S, AA x in S, x @ e = e @ x =x$
# existência do inverso:$ AA x in S, EE y in S, x @ y = y @ x = e$
# comutativa: $ AA x,y in S, x @ y= y @ x$
# distributiva à esquerda: $ AA x,y,z in S x @(y ox z)=(x @y) ox (x @ z)$
# distributiva à direita: $ AA x,y,z in S (y ox z) @ x = (y @ x) ox (z @ x)$
> Exercício: mostrar que o elemento neutro, se existe, é único.
>
> Exercício: qual o inverso do elemento neutro?
>
! Ordenação
Um sistema $< P, le >$ é parcialmente ordenado sse satisfaz as propriedades "antissimétrica", "reflexiva" e "transitiva".
Se satisfaz a propriedade de "comparabilidade", diz-se que o sistema é totalmente ordenado.
Exemplos:
$<2 ^({1,2,3}), sub >$ - ordem parcial
$<ZZ, le>$ - ordem total
! Fechos de Relações
Seja $R sub S xx S$.
Fecho transitivo de R é $R^+$, definido por
1) $aRb -> a R^+ b$
2) $(a,b) in R^+$ e $(b,c) in R -> (a,c) in R^+$
3) Nada mais em $R^+$ que não venha de (1) ou de (2)
$R^+$ inclui R, é transitivo e é mínimo.
Fecho reflexivo e transitivo $R^**$ de R:
$R^+ uu {(a,a)| a in S}$
Exemplo R={(1,2),(2,2),(2,3)} e S={1,2,3}
$R^+={(1,2),(2,2),(2,3),(1,3)}$
$R^**={(1,1),(1,2),(1,3),(2,2),(2,3),(3,3)}$
<<tiddler NextTiddler with: [[Cardinalidade de Conjuntos Infinitos]]>>
/***
|Name:|QuickOpenTagPlugin|
|Description:|Changes tag links to make it easier to open tags as tiddlers|
|Version:|3.0.1 ($Rev: 3861 $)|
|Date:|$Date: 2008-03-08 10:53:09 +1000 (Sat, 08 Mar 2008) $|
|Source:|http://mptw.tiddlyspot.com/#QuickOpenTagPlugin|
|Author:|Simon Baird <simon.baird@gmail.com>|
|License:|http://mptw.tiddlyspot.com/#TheBSDLicense|
***/
//{{{
config.quickOpenTag = {
dropdownChar: (document.all ? "\u25bc" : "\u25be"), // the little one doesn't work in IE?
createTagButton: function(place,tag,excludeTiddler) {
// little hack so we can do this: <<tag PrettyTagName|RealTagName>>
var splitTag = tag.split("|");
var pretty = tag;
if (splitTag.length == 2) {
tag = splitTag[1];
pretty = splitTag[0];
}
var sp = createTiddlyElement(place,"span",null,"quickopentag");
createTiddlyText(createTiddlyLink(sp,tag,false),pretty);
var theTag = createTiddlyButton(sp,config.quickOpenTag.dropdownChar,
config.views.wikified.tag.tooltip.format([tag]),onClickTag);
theTag.setAttribute("tag",tag);
if (excludeTiddler)
theTag.setAttribute("tiddler",excludeTiddler);
return(theTag);
},
miniTagHandler: function(place,macroName,params,wikifier,paramString,tiddler) {
var tagged = store.getTaggedTiddlers(tiddler.title);
if (tagged.length > 0) {
var theTag = createTiddlyButton(place,config.quickOpenTag.dropdownChar,
config.views.wikified.tag.tooltip.format([tiddler.title]),onClickTag);
theTag.setAttribute("tag",tiddler.title);
theTag.className = "miniTag";
}
},
allTagsHandler: function(place,macroName,params) {
var tags = store.getTags(params[0]);
var filter = params[1]; // new feature
var ul = createTiddlyElement(place,"ul");
if(tags.length == 0)
createTiddlyElement(ul,"li",null,"listTitle",this.noTags);
for(var t=0; t<tags.length; t++) {
var title = tags[t][0];
if (!filter || (title.match(new RegExp('^'+filter)))) {
var info = getTiddlyLinkInfo(title);
var theListItem =createTiddlyElement(ul,"li");
var theLink = createTiddlyLink(theListItem,tags[t][0],true);
var theCount = " (" + tags[t][1] + ")";
theLink.appendChild(document.createTextNode(theCount));
var theDropDownBtn = createTiddlyButton(theListItem," " +
config.quickOpenTag.dropdownChar,this.tooltip.format([tags[t][0]]),onClickTag);
theDropDownBtn.setAttribute("tag",tags[t][0]);
}
}
},
// todo fix these up a bit
styles: [
"/*{{{*/",
"/* created by QuickOpenTagPlugin */",
".tagglyTagged .quickopentag, .tagged .quickopentag ",
" { margin-right:1.2em; border:1px solid #eee; padding:2px; padding-right:0px; padding-left:1px; }",
".quickopentag .tiddlyLink { padding:2px; padding-left:3px; }",
".quickopentag a.button { padding:1px; padding-left:2px; padding-right:2px;}",
"/* extra specificity to make it work right */",
"#displayArea .viewer .quickopentag a.button, ",
"#displayArea .viewer .quickopentag a.tiddyLink, ",
"#mainMenu .quickopentag a.tiddyLink, ",
"#mainMenu .quickopentag a.tiddyLink ",
" { border:0px solid black; }",
"#displayArea .viewer .quickopentag a.button, ",
"#mainMenu .quickopentag a.button ",
" { margin-left:0px; padding-left:2px; }",
"#displayArea .viewer .quickopentag a.tiddlyLink, ",
"#mainMenu .quickopentag a.tiddlyLink ",
" { margin-right:0px; padding-right:0px; padding-left:0px; margin-left:0px; }",
"a.miniTag {font-size:150%;} ",
"#mainMenu .quickopentag a.button ",
" /* looks better in right justified main menus */",
" { margin-left:0px; padding-left:2px; margin-right:0px; padding-right:0px; }",
"#topMenu .quickopentag { padding:0px; margin:0px; border:0px; }",
"#topMenu .quickopentag .tiddlyLink { padding-right:1px; margin-right:0px; }",
"#topMenu .quickopentag .button { padding-left:1px; margin-left:0px; border:0px; }",
"/*}}}*/",
""].join("\n"),
init: function() {
// we fully replace these builtins. can't hijack them easily
window.createTagButton = this.createTagButton;
config.macros.allTags.handler = this.allTagsHandler;
config.macros.miniTag = { handler: this.miniTagHandler };
config.shadowTiddlers["QuickOpenTagStyles"] = this.styles;
store.addNotification("QuickOpenTagStyles",refreshStyles);
}
}
config.quickOpenTag.init();
//}}}
/***
|Name:|RenameTagsPlugin|
|Description:|Allows you to easily rename or delete tags across multiple tiddlers|
|Version:|3.0 ($Rev: 5501 $)|
|Date:|$Date: 2008-06-10 23:11:55 +1000 (Tue, 10 Jun 2008) $|
|Source:|http://mptw.tiddlyspot.com/#RenameTagsPlugin|
|Author:|Simon Baird <simon.baird@gmail.com>|
|License|http://mptw.tiddlyspot.com/#TheBSDLicense|
Rename a tag and you will be prompted to rename it in all its tagged tiddlers.
***/
//{{{
config.renameTags = {
prompts: {
rename: "Rename the tag '%0' to '%1' in %2 tidder%3?",
remove: "Remove the tag '%0' from %1 tidder%2?"
},
removeTag: function(tag,tiddlers) {
store.suspendNotifications();
for (var i=0;i<tiddlers.length;i++) {
store.setTiddlerTag(tiddlers[i].title,false,tag);
}
store.resumeNotifications();
store.notifyAll();
},
renameTag: function(oldTag,newTag,tiddlers) {
store.suspendNotifications();
for (var i=0;i<tiddlers.length;i++) {
store.setTiddlerTag(tiddlers[i].title,false,oldTag); // remove old
store.setTiddlerTag(tiddlers[i].title,true,newTag); // add new
}
store.resumeNotifications();
store.notifyAll();
},
storeMethods: {
saveTiddler_orig_renameTags: TiddlyWiki.prototype.saveTiddler,
saveTiddler: function(title,newTitle,newBody,modifier,modified,tags,fields,clearChangeCount,created) {
if (title != newTitle) {
var tagged = this.getTaggedTiddlers(title);
if (tagged.length > 0) {
// then we are renaming a tag
if (confirm(config.renameTags.prompts.rename.format([title,newTitle,tagged.length,tagged.length>1?"s":""])))
config.renameTags.renameTag(title,newTitle,tagged);
if (!this.tiddlerExists(title) && newBody == "")
// dont create unwanted tiddler
return null;
}
}
return this.saveTiddler_orig_renameTags(title,newTitle,newBody,modifier,modified,tags,fields,clearChangeCount,created);
},
removeTiddler_orig_renameTags: TiddlyWiki.prototype.removeTiddler,
removeTiddler: function(title) {
var tagged = this.getTaggedTiddlers(title);
if (tagged.length > 0)
if (confirm(config.renameTags.prompts.remove.format([title,tagged.length,tagged.length>1?"s":""])))
config.renameTags.removeTag(title,tagged);
return this.removeTiddler_orig_renameTags(title);
}
},
init: function() {
merge(TiddlyWiki.prototype,this.storeMethods);
}
}
config.renameTags.init();
//}}}
/***
|Name:|SVGIncluderPlugin|
|Description:|Includes ASCIISVG in your tiddlers with a plugin|
|Version:|1.0 ($Rev: 0000 $)|
|Date:|$Date: 2008-07-05$|
|Source:|to be announced|
|Author:|Mathifier|
|License:|GPL|
***/
//{{{
/* ASCIIsvg.js
==============
JavaScript routines to dynamically generate Scalable Vector Graphics
using a mathematical xy-coordinate system (y increases upwards) and
very intuitive JavaScript commands (no programming experience required).
ASCIIsvg.js is good for learning math and illustrating online math texts.
Works with Internet Explorer+Adobe SVGviewer and SVG enabled Mozilla/Firefox.
Ver 1.2.7 Sep 13, 2005 (c) Peter Jipsen http://www.chapman.edu/~jipsen
Latest version at http://www.chapman.edu/~jipsen/svg/ASCIIsvg.js
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.*/
var checkIfSVGavailable = true;
var notifyIfNoSVG = true;
var alertIfNoSVG = false;
var xunitlength = 20; // pixels
var yunitlength = 20; // pixels
var origin = [0,0]; // in pixels (default is bottom left corner)
var defaultwidth = 300; defaultheight = 200; defaultborder = 0;
var border = defaultborder;
var strokewidth, strokedasharray, stroke, fill;
var fontstyle, fontfamily, fontsize, fontweight, fontstroke, fontfill;
var markerstrokewidth = "1";
var markerstroke = "black";
var markerfill = "yellow";
var marker = "none";
var arrowfill = stroke;
var dotradius = 4;
var ticklength = 4;
var axesstroke = "black";
var gridstroke = "grey";
var pointerpos = null;
var coordinates = null;
var above = "above";
var below = "below";
var left = "left";
var right = "right";
var aboveleft = "aboveleft";
var aboveright = "aboveright";
var belowleft = "belowleft";
var belowright = "belowright";
var cpi = "\u03C0", ctheta = "\u03B8";
var pi = Math.PI, ln = Math.log, e = Math.E;
var arcsin = Math.asin, arccos = Math.acos, arctan = Math.atan;
var sec = function(x) { return 1/Math.cos(x) };
var csc = function(x) { return 1/Math.sin(x) };
var cot = function(x) { return 1/Math.tan(x) };
var xmin, xmax, ymin, ymax, xscl, yscl,
xgrid, ygrid, xtick, ytick, initialized;
var isIE = document.createElementNS==null;
var picture, svgpicture, doc, width, height, a, b, c, d, i, n, p, t, x, y;
var arcsec = function(x) { return arccos(1/x) };
var arccsc = function(x) { return arcsin(1/x) };
var arccot = function(x) { return arctan(1/x) };
var sinh = function(x) { return (Math.exp(x)-Math.exp(-x))/2 };
var cosh = function(x) { return (Math.exp(x)+Math.exp(-x))/2 };
var tanh =
function(x) { return (Math.exp(x)-Math.exp(-x))/(Math.exp(x)+Math.exp(-x)) };
var sech = function(x) { return 1/cosh(x) };
var csch = function(x) { return 1/sinh(x) };
var coth = function(x) { return 1/tanh(x) };
var arcsinh = function(x) { return ln(x+Math.sqrt(x*x+1)) };
var arccosh = function(x) { return ln(x+Math.sqrt(x*x-1)) };
var arctanh = function(x) { return ln((1+x)/(1-x))/2 };
var sech = function(x) { return 1/cosh(x) };
var csch = function(x) { return 1/sinh(x) };
var coth = function(x) { return 1/tanh(x) };
var arcsech = function(x) { return arccosh(1/x) };
var arccsch = function(x) { return arcsinh(1/x) };
var arccoth = function(x) { return arctanh(1/x) };
var sign = function(x) { return (x==0?0:(x<0?-1:1)) };
function factorial(x,n) {
if (n==null) n=1;
for (var i=x-n; i>0; i-=n) x*=i;
return (x<0?NaN:(x==0?1:x));
}
function C(x,k) {
var res=1;
for (var i=0; i<k; i++) res*=(x-i)/(k-i);
return res;
}
function chop(x,n) {
if (n==null) n=0;
return Math.floor(x*Math.pow(10,n))/Math.pow(10,n);
}
function ran(a,b,n) {
if (n==null) n=0;
return chop((b+Math.pow(10,-n)-a)*Math.random()+a,n);
}
function myCreateElementXHTML(t) {
if (isIE) return document.createElement(t);
else return document.createElementNS("http://www.w3.org/1999/xhtml",t);
}
function isSVGavailable() {
var nd = myCreateElementXHTML("center");
nd.appendChild(document.createTextNode("To view the "));
var an = myCreateElementXHTML("a");
an.appendChild(document.createTextNode("ASCIIsvg"));
an.setAttribute("href","http://www.chapman.edu/~jipsen/asciisvg.html");
nd.appendChild(an);
nd.appendChild(document.createTextNode(" images use Internet Explorer 6+"));
an = myCreateElementXHTML("a");
an.appendChild(document.createTextNode("Adobe SVGviewer 3.02"));
an.setAttribute("href","http://www.adobe.com/svg");
nd.appendChild(an);
nd.appendChild(document.createTextNode(" or "));
an = myCreateElementXHTML("a");
an.appendChild(document.createTextNode("SVG enabled Mozilla/Firefox"));
an.setAttribute("href",
"http://www.chapman.edu/~jipsen/svg/svgenabledmozillafirefox.html");
nd.appendChild(an);
if (navigator.appName.slice(0,8)=="Netscape")
if (window['SVGElement']) return null;
else return nd;
else if (navigator.appName.slice(0,9)=="Microsoft")
try {
var oSVG=eval("new ActiveXObject('Adobe.SVGCtl.3');");
return null;
} catch (e) {
return nd;
}
else return nd;
}
function less(x,y) { return x < y } // used for scripts in XML files
// since IE does not handle CDATA well
function setText(st,id) {
var node = document.getElementById(id);
if (node!=null)
if (node.childNodes.length!=0) node.childNodes[0].nodeValue = st;
else node.appendChild(document.createTextNode(st));
}
function myCreateElementSVG(t) {
if (isIE) return doc.createElement(t);
else return doc.createElementNS("http://www.w3.org/2000/svg",t);
}
function showNames(obj) {
var st,str="";
for (st in obj) str+=st+", ";
return str;
}
function getX() {
return (doc.getElementById("pointerpos").getAttribute("cx")-origin[0])/xunitlength;
}
function getY() {
return (height-origin[1]-doc.getElementById("pointerpos").getAttribute("cy"))/yunitlength;
}
function mousemove_listener(evt) {
if (svgpicture.getAttribute("xbase")!=null)
pointerpos.cx.baseVal.value = evt.clientX-svgpicture.getAttribute("xbase");
if (svgpicture.getAttribute("ybase")!=null)
pointerpos.cy.baseVal.value = evt.clientY-svgpicture.getAttribute("ybase");
}
function top_listener(evt) {
svgpicture.setAttribute("ybase",evt.clientY);
}
function bottom_listener(evt) {
svgpicture.setAttribute("ybase",evt.clientY-height+1);
}
function left_listener(evt) {
svgpicture.setAttribute("xbase",evt.clientX);
}
function right_listener(evt) {
svgpicture.setAttribute("xbase",evt.clientX-width+1);
}
function drawPictures() { // main routine; called after webpage has loaded
var src, id, dsvg, onmov, nd, node, ht, index;
var pictures = document.getElementsByTagName("textarea");
for (index = 0; index<pictures.length; index++)
if (pictures[index].className=="ASCIIsvg"){
pictures[index].style.display="none"; // hide the textarea
}
pictures = document.getElementsByTagName("embed");
var len = pictures.length;
if (checkIfSVGavailable) {
nd = isSVGavailable();
if (nd != null && notifyIfNoSVG && len>0)
if (alertIfNoSVG)
alert("To view the SVG pictures in Internet Explorer\n\
download the free Adobe SVGviewer from www.adobe.com/svg or\n\
use Firefox 1.5 preview (called Deerpark)");
else {
var ASbody = document.getElementsByTagName("body")[0];
ASbody.insertBefore(nd,ASbody.childNodes[0]);
}
}
if (nd == null) {
for (index = 0; index < len; index++) {
xmin = null; xmax = null; ymin = null; ymax = null;
xscl = null; xgrid = null; yscl = null; ygrid = null;
initialized = false;
picture = (isIE ? pictures[index] : pictures[0]);
src = picture.getAttribute("script");
if (src==null) src = "";
ht = picture.getAttribute("height");
if (ht==null) ht ="";
if (ht!="") {defaultborder = 25; border = 25;}
if (ht=="" || src=="")
if (document.getElementById("picture"+(index+1)+"input")==null) {
if (isIE && src.indexOf("nobutton()")==-1)
picture.parentNode.insertBefore(myCreateElementXHTML("br"),picture);
node = myCreateElementXHTML("textarea");
node.setAttribute("rows","10");
node.setAttribute("cols","60");
// node.setAttribute("style","display:block");
if (isIE) src = src.replace(/([^\r])\n/g,"$1\r").slice(1);
node.appendChild(document.createTextNode(src));
if (src.indexOf("showcode()")==-1) node.style.display = "none";
node.setAttribute("id","picture"+(index+1)+"input");
picture.parentNode.insertBefore(node,picture);
if (src.indexOf("nobutton()")==-1) {
picture.parentNode.insertBefore(myCreateElementXHTML("br"),picture);
node = myCreateElementXHTML("button");
if (isIE) node.onclick = function() { showHideCode(this) };
else node.setAttribute("onclick","showHideCode(this)");
node.appendChild(document.createTextNode("Show/Hide"));
picture.parentNode.insertBefore(node,picture);
node = myCreateElementXHTML("button");
if (isIE) node.onclick = ASfn[index];
else node.setAttribute("onclick","updatePicture("+index+")");
node.appendChild(document.createTextNode("Update"));
if (src.indexOf("showCode()")==-1) node.style.display = "none";
picture.parentNode.insertBefore(node,picture);
/* node = myCreateElementXHTML("span");
// node.setAttribute("id","AScoord"+index);
node.appendChild(document.createTextNode("(x,y)"));
picture.parentNode.insertBefore(node,picture);
*/
picture.parentNode.insertBefore(myCreateElementXHTML("br"),picture);
}
if (isIE) picture.onmousemove = ASupdateCoords[index];
else picture.setAttribute("onmousemove","updateCoords"+index+"()");
} else src = document.getElementById("picture"+(index+1)+"input").value;
src = src.replace(/plot\(\x20*([^\"f\[][^\n\r]+?)\,/g,"plot\(\"$1\",");
src = src.replace(/plot\(\x20*([^\"f\[][^\n\r]+)\)/g,"plot(\"$1\")");
src = src.replace(/([0-9])([a-zA-Z])/g,"$1*$2");
src = src.replace(/\)([\(0-9a-zA-Z])/g,"\)*$1");
// eval(src.replace(/\s\s/g,";")); //for XML version
id = picture.getAttribute("id");
dsvg = picture.getAttribute("src");
onmov = picture.getAttribute("onmousemove");
if (id == null || id == "") {
id = "picture"+(index+1);
picture.setAttribute("id",id);
}
//axes();
try {
with (Math) eval(src);
} catch(err) {
if (err=="wait") return false;
else {
var st,str="";
for (st in err) str+=st;
alert(err.name+"\n"+err.number+"\n"+err.message+"\n"+err.description+"\n"+src)
}
}
if (isIE) src = src.replace(/([^\r])\n/g,"$1\r");
setText("<embed width=\""+width+"\" height=\""+height+"\" src=\""+
dsvg+"\" "+(onmov!=null?"onmousemove=\""+onmov+"\"":"")+
(isIE?"\r":"\n")+"script=\'"+src+"\'>",id+"script");
// setText(src.replace(/\s\s/g,"\r"),id+"script"); //for XML version
}
}
}
function switchTo(id) {
//alert(id);
picture = document.getElementById(id);
width = picture.getAttribute("width")-0;
height = picture.getAttribute("height")-0;
strokewidth = "1" // pixel
stroke = "black"; // default line color
fill = "none"; // default fill color
marker = "none";
if ((picture.nodeName == "EMBED" || picture.nodeName == "embed") && isIE) {
svgpicture = picture.getSVGDocument().getElementById("root");
doc = picture.getSVGDocument();
} else {
picture.setAttribute("onmousemove","updateCoords"+(id.slice(id.length-1)-1)+"()");
//alert(picture.getAttribute("onmousemove")+"***");
svgpicture = picture;
doc = document;
}
xunitlength = svgpicture.getAttribute("xunitlength")-0;
yunitlength = svgpicture.getAttribute("yunitlength")-0;
xmin = svgpicture.getAttribute("xmin")-0;
xmax = svgpicture.getAttribute("xmax")-0;
ymin = svgpicture.getAttribute("ymin")-0;
ymax = svgpicture.getAttribute("ymax")-0;
origin = [svgpicture.getAttribute("ox")-0,svgpicture.getAttribute("oy")-0];
}
function updatePicture(obj) {
//alert(typeof obj)
var src = document.getElementById((typeof obj=="string"?
obj:"picture"+(obj+1)+"input")).value;
xmin = null; xmax = null; ymin = null; ymax = null;
xscl = null; xgrid = null; yscl = null; ygrid = null;
initialized = false;
switchTo((typeof obj=="string"?obj.slice(0,8):"picture"+(obj+1)));
src = src.replace(/plot\(\x20*([^\"f\[][^\n\r]+?)\,/g,"plot\(\"$1\",");
src = src.replace(/plot\(\x20*([^\"f\[][^\n\r]+)\)/g,"plot(\"$1\")");
src = src.replace(/([0-9])([a-zA-Z])/g,"$1*$2");
src = src.replace(/\)([\(0-9a-zA-Z])/g,"\)*$1");
//alert(src);
try {
with (Math) eval(src);
} catch(err) {alert(err+"\n"+src)}
}
function showHideCode(obj) {
var node = obj.nextSibling;
while (node != null && node.nodeName != "BUTTON" &&
node.nodeName != "button") node = node.nextSibling;
if (node.style.display == "none") node.style.display = "";
else node.style.display = "none";
while (node != null && node.nodeName != "TEXTAREA" &&
node.nodeName != "textarea") node = node.previousSibling;
if (node.style.display == "none") node.style.display = "";
else node.style.display = "none";
// updatePicture(node.getAttribute("id"));
}
function hideCode() { //do nothing
}
function showcode() { //do nothing
}
function nobutton() { //do nothing
}
function setBorder(x) { border = x }
function initPicture(x_min,x_max,y_min,y_max) {
if (!initialized) {
strokewidth = "1"; // pixel
strokedasharray = null;
stroke = "black"; // default line color
fill = "none"; // default fill color
fontstyle = "italic"; // default shape for text labels
fontfamily = "times"; // default font
fontsize = "16"; // default size
fontweight = "normal";
fontstroke = "none"; // default font outline color
fontfill = "none"; // default font color
marker = "none";
initialized = true;
if (x_min!=null) xmin = x_min;
if (x_max!=null) xmax = x_max;
if (y_min!=null) ymin = y_min;
if (y_max!=null) ymax = y_max;
if (xmin==null) xmin = -5;
if (xmax==null) xmax = 5;
if (typeof xmin != "number" || typeof xmax != "number" || xmin >= xmax)
alert("Picture requires at least two numbers: xmin < xmax");
else if (y_max != null && (typeof y_min != "number" ||
typeof y_max != "number" || y_min >= y_max))
alert("initPicture(xmin,xmax,ymin,ymax) requires numbers ymin < ymax");
else {
if (width==null) width = picture.getAttribute("width");
else picture.setAttribute("width",width);
if (width==null || width=="") width=defaultwidth;
if (height==null) height = picture.getAttribute("height");
else picture.setAttribute("height",height);
if (height==null || height=="") height=defaultheight;
xunitlength = (width-2*border)/(xmax-xmin);
yunitlength = xunitlength;
//alert(xmin+" "+xmax+" "+ymin+" "+ymax)
if (ymin==null) {
origin = [-xmin*xunitlength+border,height/2];
ymin = -(height-2*border)/(2*yunitlength);
ymax = -ymin;
} else {
if (ymax!=null) yunitlength = (height-2*border)/(ymax-ymin);
else ymax = (height-2*border)/yunitlength + ymin;
origin = [-xmin*xunitlength+border,-ymin*yunitlength+border];
}
if (isIE) {
//alert(picture.FULLSCREEN+"\n"+picture.script+"\n"+showNames(picture));
if (picture.FULLSCREEN==undefined) {
setTimeout('drawPictures()',100);
throw "wait";
}
svgpicture = picture.getSVGDocument().getElementById("root");
if (svgpicture==null) {
setTimeout('drawPictures()',100);
throw "wait";
}
while (svgpicture.childNodes.length()>5)
svgpicture.removeChild(svgpicture.lastChild);
svgpicture.setAttribute("width",width);
svgpicture.setAttribute("height",height);
doc = picture.getSVGDocument();
} else {
var qnode = document.createElementNS("http://www.w3.org/2000/svg","svg");
qnode.setAttribute("id",picture.getAttribute("id"));
qnode.setAttribute("style","display:inline");
qnode.setAttribute("width",picture.getAttribute("width"));
qnode.setAttribute("height",picture.getAttribute("height"));
if (picture.parentNode!=null)
picture.parentNode.replaceChild(qnode,picture);
else
svgpicture.parentNode.replaceChild(qnode,svgpicture);
svgpicture = qnode;
doc = document;
pointerpos = doc.getElementById("pointerpos");
if (pointerpos==null) {
pointerpos = myCreateElementSVG("circle");
pointerpos.setAttribute("id","pointerpos");
pointerpos.setAttribute("cx",0);
pointerpos.setAttribute("cy",0);
pointerpos.setAttribute("r",0.5);
pointerpos.setAttribute("fill","red");
svgpicture.appendChild(pointerpos);
}
}
svgpicture.setAttribute("xunitlength",xunitlength);
svgpicture.setAttribute("yunitlength",yunitlength);
svgpicture.setAttribute("xmin",xmin);
svgpicture.setAttribute("xmax",xmax);
svgpicture.setAttribute("ymin",ymin);
svgpicture.setAttribute("ymax",ymax);
svgpicture.setAttribute("ox",origin[0]);
svgpicture.setAttribute("oy",origin[1]);
var node = myCreateElementSVG("rect");
node.setAttribute("x","0");
node.setAttribute("y","0");
node.setAttribute("width",width);
node.setAttribute("height",height);
node.setAttribute("style","stroke-width:1;fill:white");
svgpicture.appendChild(node);
if (!isIE && picture.getAttribute("onmousemove")!=null) {
svgpicture.addEventListener("mousemove", mousemove_listener, true);
var st = picture.getAttribute("onmousemove");
svgpicture.addEventListener("mousemove", eval(st.slice(0,st.indexOf("("))), true);
node = myCreateElementSVG("polyline");
node.setAttribute("points","0,0 "+width+",0");
node.setAttribute("style","stroke:white; stroke-width:3");
node.addEventListener("mousemove", top_listener, true);
svgpicture.appendChild(node);
node = myCreateElementSVG("polyline");
node.setAttribute("points","0,"+height+" "+width+","+height);
node.setAttribute("style","stroke:white; stroke-width:3");
node.addEventListener("mousemove", bottom_listener, true);
svgpicture.appendChild(node);
node = myCreateElementSVG("polyline");
node.setAttribute("points","0,0 0,"+height);
node.setAttribute("style","stroke:white; stroke-width:3");
node.addEventListener("mousemove", left_listener, true);
svgpicture.appendChild(node);
node = myCreateElementSVG("polyline");
node.setAttribute("points",(width-1)+",0 "+(width-1)+","+height);
node.setAttribute("style","stroke:white; stroke-width:3");
node.addEventListener("mousemove", right_listener, true);
svgpicture.appendChild(node);
}
border = defaultborder;
}
}
}
function line(p,q,id) { // segment connecting points p,q (coordinates in units)
var node;
if (id!=null) node = doc.getElementById(id);
if (node==null) {
node = myCreateElementSVG("path");
node.setAttribute("id", id);
svgpicture.appendChild(node);
}
node.setAttribute("d","M"+(p[0]*xunitlength+origin[0])+","+
(height-p[1]*yunitlength-origin[1])+" "+
(q[0]*xunitlength+origin[0])+","+(height-q[1]*yunitlength-origin[1]));
node.setAttribute("stroke-width", strokewidth);
if (strokedasharray!=null)
node.setAttribute("stroke-dasharray", strokedasharray);
node.setAttribute("stroke", stroke);
node.setAttribute("fill", fill);
if (marker=="dot" || marker=="arrowdot") {
ASdot(p,4,markerstroke,markerfill);
if (marker=="arrowdot") arrowhead(p,q);
ASdot(q,4,markerstroke,markerfill);
} else if (marker=="arrow") arrowhead(p,q);
}
function path(plist,id,c) {
if (c==null) c="";
var node, st, i;
if (id!=null) node = doc.getElementById(id);
if (node==null) {
node = myCreateElementSVG("path");
node.setAttribute("id", id);
svgpicture.appendChild(node);
}
if (typeof plist == "string") st = plist;
else {
st = "M";
st += (plist[0][0]*xunitlength+origin[0])+","+
(height-plist[0][1]*yunitlength-origin[1])+" "+c;
for (i=1; i<plist.length; i++)
st += (plist[i][0]*xunitlength+origin[0])+","+
(height-plist[i][1]*yunitlength-origin[1])+" ";
}
node.setAttribute("d", st);
node.setAttribute("stroke-width", strokewidth);
if (strokedasharray!=null)
node.setAttribute("stroke-dasharray", strokedasharray);
node.setAttribute("stroke", stroke);
node.setAttribute("fill", fill);
if (marker=="dot" || marker=="arrowdot")
for (i=0; i<plist.length; i++)
if (c!="C" && c!="T" || i!=1 && i!=2)
ASdot(plist[i],4,markerstroke,markerfill);
}
function curve(plist,id) {
path(plist,id,"T");
}
function circle(center,radius,id) { // coordinates in units
var node;
if (id!=null) node = doc.getElementById(id);
if (node==null) {
node = myCreateElementSVG("circle");
node.setAttribute("id", id);
svgpicture.appendChild(node);
}
node.setAttribute("cx",center[0]*xunitlength+origin[0]);
node.setAttribute("cy",height-center[1]*yunitlength-origin[1]);
node.setAttribute("r",radius*xunitlength);
node.setAttribute("stroke-width", strokewidth);
node.setAttribute("stroke", stroke);
node.setAttribute("fill", fill);
}
function loop(p,d,id) {
// d is a direction vector e.g. [1,0] means loop starts in that direction
if (d==null) d=[1,0];
path([p,[p[0]+d[0],p[1]+d[1]],[p[0]-d[1],p[1]+d[0]],p],id,"C");
if (marker=="arrow" || marker=="arrowdot")
arrowhead([p[0]+Math.cos(1.4)*d[0]-Math.sin(1.4)*d[1],
p[1]+Math.sin(1.4)*d[0]+Math.cos(1.4)*d[1]],p);
}
function arc(start,end,radius,id) { // coordinates in units
var node, v;
//alert([fill, stroke, origin, xunitlength, yunitlength, height])
if (id!=null) node = doc.getElementById(id);
if (radius==null) {
v=[end[0]-start[0],end[1]-start[1]];
radius = Math.sqrt(v[0]*v[0]+v[1]*v[1]);
}
if (node==null) {
node = myCreateElementSVG("path");
node.setAttribute("id", id);
svgpicture.appendChild(node);
}
node.setAttribute("d","M"+(start[0]*xunitlength+origin[0])+","+
(height-start[1]*yunitlength-origin[1])+" A"+radius*xunitlength+","+
radius*yunitlength+" 0 0,0 "+(end[0]*xunitlength+origin[0])+","+
(height-end[1]*yunitlength-origin[1]));
node.setAttribute("stroke-width", strokewidth);
node.setAttribute("stroke", stroke);
node.setAttribute("fill", fill);
if (marker=="arrow" || marker=="arrowdot") {
u = [(end[1]-start[1])/4,(start[0]-end[0])/4];
v = [(end[0]-start[0])/2,(end[1]-start[1])/2];
//alert([u,v])
v = [start[0]+v[0]+u[0],start[1]+v[1]+u[1]];
} else v=[start[0],start[1]];
if (marker=="dot" || marker=="arrowdot") {
ASdot(start,4,markerstroke,markerfill);
if (marker=="arrowdot") arrowhead(v,end);
ASdot(end,4,markerstroke,markerfill);
} else if (marker=="arrow") arrowhead(v,end);
}
function ellipse(center,rx,ry,id) { // coordinates in units
var node;
if (id!=null) node = doc.getElementById(id);
if (node==null) {
node = myCreateElementSVG("ellipse");
node.setAttribute("id", id);
svgpicture.appendChild(node);
}
node.setAttribute("cx",center[0]*xunitlength+origin[0]);
node.setAttribute("cy",height-center[1]*yunitlength-origin[1]);
node.setAttribute("rx",rx*xunitlength);
node.setAttribute("ry",ry*yunitlength);
node.setAttribute("stroke-width", strokewidth);
node.setAttribute("stroke", stroke);
node.setAttribute("fill", fill);
}
function rect(p,q,id,rx,ry) { // opposite corners in units, rounded by radii
var node;
if (id!=null) node = doc.getElementById(id);
if (node==null) {
node = myCreateElementSVG("rect");
node.setAttribute("id", id);
svgpicture.appendChild(node);
}
node.setAttribute("x",p[0]*xunitlength+origin[0]);
node.setAttribute("y",height-q[1]*yunitlength-origin[1]);
node.setAttribute("width",(q[0]-p[0])*xunitlength);
node.setAttribute("height",(q[1]-p[1])*yunitlength);
if (rx!=null) node.setAttribute("rx",rx*xunitlength);
if (ry!=null) node.setAttribute("ry",ry*yunitlength);
node.setAttribute("stroke-width", strokewidth);
node.setAttribute("stroke", stroke);
node.setAttribute("fill", fill);
}
function text(p,st,pos,id,fontsty) {
var textanchor = "middle";
var dx = 0; var dy = fontsize/3;
if (pos!=null) {
if (pos.slice(0,5)=="above") dy = -fontsize/2;
if (pos.slice(0,5)=="below") dy = fontsize-0;
if (pos.slice(0,5)=="right" || pos.slice(5,10)=="right") {
textanchor = "start";
dx = fontsize/2;
}
if (pos.slice(0,4)=="left" || pos.slice(5,9)=="left") {
textanchor = "end";
dx = -fontsize/2;
}
}
var node;
if (id!=null) node = doc.getElementById(id);
if (node==null) {
node = myCreateElementSVG("text");
node.setAttribute("id", id);
svgpicture.appendChild(node);
node.appendChild(doc.createTextNode(st));
}
node.lastChild.nodeValue = st;
node.setAttribute("x",p[0]*xunitlength+origin[0]+dx);
node.setAttribute("y",height-p[1]*yunitlength-origin[1]+dy);
node.setAttribute("font-style",(fontsty!=null?fontsty:fontstyle));
node.setAttribute("font-family",fontfamily);
node.setAttribute("font-size",fontsize);
node.setAttribute("font-weight",fontweight);
node.setAttribute("text-anchor",textanchor);
if (fontstroke!="none") node.setAttribute("stroke",fontstroke);
if (fontfill!="none") node.setAttribute("fill",fontfill);
return p;
}
function ASdot(center,radius,s,f) { // coordinates in units, radius in pixel
if (s==null) s = stroke; if (f==null) f = fill;
var node = myCreateElementSVG("circle");
node.setAttribute("cx",center[0]*xunitlength+origin[0]);
node.setAttribute("cy",height-center[1]*yunitlength-origin[1]);
node.setAttribute("r",radius);
node.setAttribute("stroke-width", strokewidth);
node.setAttribute("stroke", s);
node.setAttribute("fill", f);
svgpicture.appendChild(node);
}
function dot(center, typ, label, pos, id) {
var node;
var cx = center[0]*xunitlength+origin[0];
var cy = height-center[1]*yunitlength-origin[1];
if (id!=null) node = doc.getElementById(id);
if (typ=="+" || typ=="-" || typ=="|") {
if (node==null) {
node = myCreateElementSVG("path");
node.setAttribute("id", id);
svgpicture.appendChild(node);
}
if (typ=="+") {
node.setAttribute("d",
" M "+(cx-ticklength)+" "+cy+" L "+(cx+ticklength)+" "+cy+
" M "+cx+" "+(cy-ticklength)+" L "+cx+" "+(cy+ticklength));
node.setAttribute("stroke-width", .5);
node.setAttribute("stroke", axesstroke);
} else {
if (typ=="-") node.setAttribute("d",
" M "+(cx-ticklength)+" "+cy+" L "+(cx+ticklength)+" "+cy);
else node.setAttribute("d",
" M "+cx+" "+(cy-ticklength)+" L "+cx+" "+(cy+ticklength));
node.setAttribute("stroke-width", strokewidth);
node.setAttribute("stroke", stroke);
}
} else {
if (node==null) {
node = myCreateElementSVG("circle");
node.setAttribute("id", id);
svgpicture.appendChild(node);
}
node.setAttribute("cx",cx);
node.setAttribute("cy",cy);
node.setAttribute("r",dotradius);
node.setAttribute("stroke-width", strokewidth);
node.setAttribute("stroke", stroke);
node.setAttribute("fill", (typ=="open"?"white":stroke));
}
if (label!=null)
text(center,label,(pos==null?"below":pos),(id==null?id:id+"label"))
}
function arrowhead(p,q) { // draw arrowhead at q (in units)
var up;
var v = [p[0]*xunitlength+origin[0],height-p[1]*yunitlength-origin[1]];
var w = [q[0]*xunitlength+origin[0],height-q[1]*yunitlength-origin[1]];
var u = [w[0]-v[0],w[1]-v[1]];
var d = Math.sqrt(u[0]*u[0]+u[1]*u[1]);
if (d > 0.00000001) {
u = [u[0]/d, u[1]/d];
up = [-u[1],u[0]];
var node = myCreateElementSVG("path");
node.setAttribute("d","M "+(w[0]-15*u[0]-4*up[0])+" "+
(w[1]-15*u[1]-4*up[1])+" L "+(w[0]-3*u[0])+" "+(w[1]-3*u[1])+" L "+
(w[0]-15*u[0]+4*up[0])+" "+(w[1]-15*u[1]+4*up[1])+" z");
node.setAttribute("stroke-width", markerstrokewidth);
node.setAttribute("stroke", stroke); /*was markerstroke*/
node.setAttribute("fill", stroke); /*was arrowfill*/
svgpicture.appendChild(node);
}
}
function chopZ(st) {
var k = st.indexOf(".");
if (k==-1) return st;
for (var i=st.length-1; i>k && st.charAt(i)=="0"; i--);
if (i==k) i--;
return st.slice(0,i+1);
}
function grid(dx,dy) { // for backward compatibility
axes(dx,dy,null,dx,dy)
}
function noaxes() {
if (!initialized) initPicture();
}
function axes(dx,dy,labels,gdx,gdy) {
//xscl=x is equivalent to xtick=x; xgrid=x; labels=true;
var x, y, ldx, ldy, pnode, st;
if (!initialized) initPicture();
if (typeof dx=="string") { labels = dx; dx = null; }
if (typeof dy=="string") { gdx = dy; dy = null; }
if (xscl!=null) {dx = xscl; gdx = xscl; labels = dx}
if (yscl!=null) {dy = yscl; gdy = yscl}
if (xtick!=null) {dx = xtick}
if (ytick!=null) {dy = ytick}
//alert(null)
dx = (dx==null?xunitlength:dx*xunitlength);
dy = (dy==null?dx:dy*yunitlength);
fontsize = Math.min(dx/2,dy/2,16);//alert(fontsize)
ticklength = fontsize/4;
if (xgrid!=null) gdx = xgrid;
if (ygrid!=null) gdy = ygrid;
if (gdx!=null) {
gdx = (typeof gdx=="string"?dx:gdx*xunitlength);
gdy = (gdy==null?dy:gdy*yunitlength);
pnode = myCreateElementSVG("path");
st="";
for (x = origin[0]; x<width; x = x+gdx)
st += " M"+x+",0"+" "+x+","+height;
for (x = origin[0]-gdx; x>0; x = x-gdx)
st += " M"+x+",0"+" "+x+","+height;
for (y = height-origin[1]; y<height; y = y+gdy)
st += " M0,"+y+" "+width+","+y;
for (y = height-origin[1]-gdy; y>0; y = y-gdy)
st += " M0,"+y+" "+width+","+y;
pnode.setAttribute("d",st);
pnode.setAttribute("stroke-width", .5);
pnode.setAttribute("stroke", gridstroke);
pnode.setAttribute("fill", fill);
svgpicture.appendChild(pnode);
}
pnode = myCreateElementSVG("path");
st="M0,"+(height-origin[1])+" "+width+","+
(height-origin[1])+" M"+origin[0]+",0 "+origin[0]+","+height;
for (x = origin[0]+dx; x<width; x = x+dx)
st += " M"+x+","+(height-origin[1]+ticklength)+" "+x+","+
(height-origin[1]-ticklength);
for (x = origin[0]-dx; x>0; x = x-dx)
st += " M"+x+","+(height-origin[1]+ticklength)+" "+x+","+
(height-origin[1]-ticklength);
for (y = height-origin[1]+dy; y<height; y = y+dy)
st += " M"+(origin[0]+ticklength)+","+y+" "+(origin[0]-ticklength)+","+y;
for (y = height-origin[1]-dy; y>0; y = y-dy)
st += " M"+(origin[0]+ticklength)+","+y+" "+(origin[0]-ticklength)+","+y;
if (labels!=null) with (Math) {
ldx = dx/xunitlength;
ldy = dy/yunitlength;
var ddx = floor(1.1-log(ldx)/log(10));
var ddy = floor(1.1-log(ldy)/log(10));
for (x = ldx; x<=xmax; x = x+ldx)
text([x,0],chopZ(x.toFixed(ddx)),"below");
for (x = -ldx; xmin<=x; x = x-ldx)
text([x,0],chopZ(x.toFixed(ddx)),"below");
for (y = ldy; y<=ymax; y = y+ldy)
text([0,y],chopZ(y.toFixed(ddy)),"left");
for (y = -ldy; ymin<=y; y = y-ldy)
text([0,y],chopZ(y.toFixed(ddy)),"left");
}
pnode.setAttribute("d",st);
pnode.setAttribute("stroke-width", .5);
pnode.setAttribute("stroke", axesstroke);
pnode.setAttribute("fill", fill);
svgpicture.appendChild(pnode);
}
function mathjs(st) {
//translate a math formula to js function notation
// a^b --> pow(a,b)
// na --> n*a
// (...)d --> (...)*d
// n! --> factorial(n)
// sin^-1 --> arcsin etc.
//while ^ in string, find term on left and right
//slice and concat new formula string
st = st.replace(/\s/g,"");
if (st.indexOf("^-1")!=-1) {
st = st.replace(/sin\^-1/g,"arcsin");
st = st.replace(/cos\^-1/g,"arccos");
st = st.replace(/tan\^-1/g,"arctan");
st = st.replace(/sec\^-1/g,"arcsec");
st = st.replace(/csc\^-1/g,"arccsc");
st = st.replace(/cot\^-1/g,"arccot");
st = st.replace(/sinh\^-1/g,"arcsinh");
st = st.replace(/cosh\^-1/g,"arccosh");
st = st.replace(/tanh\^-1/g,"arctanh");
st = st.replace(/sech\^-1/g,"arcsech");
st = st.replace(/csch\^-1/g,"arccsch");
st = st.replace(/coth\^-1/g,"arccoth");
}
st = st.replace(/^e$/g,"(E)");
st = st.replace(/^e([^a-zA-Z])/g,"(E)$1");
st = st.replace(/([^a-zA-Z])e([^a-zA-Z])/g,"$1(E)$2");
st = st.replace(/([0-9])([\(a-zA-Z])/g,"$1*$2");
st = st.replace(/\)([\(0-9a-zA-Z])/g,"\)*$1");
var i,j,k, ch, nested;
while ((i=st.indexOf("^"))!=-1) {
//find left argument
if (i==0) return "Error: missing argument";
j = i-1;
ch = st.charAt(j);
if (ch>="0" && ch<="9") {// look for (decimal) number
j--;
while (j>=0 && (ch=st.charAt(j))>="0" && ch<="9") j--;
if (ch==".") {
j--;
while (j>=0 && (ch=st.charAt(j))>="0" && ch<="9") j--;
}
} else if (ch==")") {// look for matching opening bracket and function name
nested = 1;
j--;
while (j>=0 && nested>0) {
ch = st.charAt(j);
if (ch=="(") nested--;
else if (ch==")") nested++;
j--;
}
while (j>=0 && (ch=st.charAt(j))>="a" && ch<="z" || ch>="A" && ch<="Z")
j--;
} else if (ch>="a" && ch<="z" || ch>="A" && ch<="Z") {// look for variable
j--;
while (j>=0 && (ch=st.charAt(j))>="a" && ch<="z" || ch>="A" && ch<="Z")
j--;
} else {
return "Error: incorrect syntax in "+st+" at position "+j;
}
//find right argument
if (i==st.length-1) return "Error: missing argument";
k = i+1;
ch = st.charAt(k);
if (ch>="0" && ch<="9" || ch=="-") {// look for signed (decimal) number
k++;
while (k<st.length && (ch=st.charAt(k))>="0" && ch<="9") k++;
if (ch==".") {
k++;
while (k<st.length && (ch=st.charAt(k))>="0" && ch<="9") k++;
}
} else if (ch=="(") {// look for matching closing bracket and function name
nested = 1;
k++;
while (k<st.length && nested>0) {
ch = st.charAt(k);
if (ch=="(") nested++;
else if (ch==")") nested--;
k++;
}
} else if (ch>="a" && ch<="z" || ch>="A" && ch<="Z") {// look for variable
k++;
while (k<st.length && (ch=st.charAt(k))>="a" && ch<="z" ||
ch>="A" && ch<="Z") k++;
} else {
return "Error: incorrect syntax in "+st+" at position "+k;
}
st = st.slice(0,j+1)+"pow("+st.slice(j+1,i)+","+st.slice(i+1,k)+")"+
st.slice(k);
}
while ((i=st.indexOf("!"))!=-1) {
//find left argument
if (i==0) return "Error: missing argument";
j = i-1;
ch = st.charAt(j);
if (ch>="0" && ch<="9") {// look for (decimal) number
j--;
while (j>=0 && (ch=st.charAt(j))>="0" && ch<="9") j--;
if (ch==".") {
j--;
while (j>=0 && (ch=st.charAt(j))>="0" && ch<="9") j--;
}
} else if (ch==")") {// look for matching opening bracket and function name
nested = 1;
j--;
while (j>=0 && nested>0) {
ch = st.charAt(j);
if (ch=="(") nested--;
else if (ch==")") nested++;
j--;
}
while (j>=0 && (ch=st.charAt(j))>="a" && ch<="z" || ch>="A" && ch<="Z")
j--;
} else if (ch>="a" && ch<="z" || ch>="A" && ch<="Z") {// look for variable
j--;
while (j>=0 && (ch=st.charAt(j))>="a" && ch<="z" || ch>="A" && ch<="Z")
j--;
} else {
return "Error: incorrect syntax in "+st+" at position "+j;
}
st = st.slice(0,j+1)+"factorial("+st.slice(j+1,i)+")"+st.slice(i+1);
}
return st;
}
function plot(fun,x_min,x_max,points,id) {
var pth = [];
var f = function(x) { return x }, g = fun;
var name = null;
if (typeof fun=="string")
eval("g = function(x){ with(Math) return "+mathjs(fun)+" }");
else if (typeof fun=="object") {
eval("f = function(t){ with(Math) return "+mathjs(fun[0])+" }");
eval("g = function(t){ with(Math) return "+mathjs(fun[1])+" }");
}
if (typeof x_min=="string") { name = x_min; x_min = xmin }
else name = id;
var min = (x_min==null?xmin:x_min);
var max = (x_max==null?xmax:x_max);
var inc = max-min-0.000001*(max-min);
inc = (points==null?inc/200:inc/points);
var gt;
//alert(typeof g(min))
for (var t = min; t <= max; t += inc) {
gt = g(t);
if (!(isNaN(gt)||Math.abs(gt)=="Infinity")) pth[pth.length] = [f(t), gt];
}
path(pth,name)
return p;
}
function slopefield(fun,dx,dy) {
var g = fun;
if (typeof fun=="string")
eval("g = function(x,y){ with(Math) return "+mathjs(fun)+" }");
var gxy,x,y,u,v,dz;
if (dx==null) dx=1;
if (dy==null) dy=1;
dz = Math.sqrt(dx*dx+dy*dy)/6;
var x_min = Math.ceil(xmin/dx);
var y_min = Math.ceil(ymin/dy);
for (x = x_min; x <= xmax; x += dx)
for (y = y_min; y <= ymax; y += dy) {
gxy = g(x,y);
if (!isNaN(gxy)) {
if (Math.abs(gxy)=="Infinity") {u = 0; v = dz;}
else {u = dz/Math.sqrt(1+gxy*gxy); v = gxy*u;}
line([x-u,y-v],[x+u,y+v]);
}
}
}
function updateCoords(ind) {
switchTo("picture"+(ind+1));
var gx=getX(), gy=getY();
if ((xmax-gx)*xunitlength > 6*fontsize || (gy-ymin)*yunitlength > 2*fontsize)
text([xmax,ymin],"("+gx.toFixed(2)+", "+gy.toFixed(2)+")",
"aboveleft","AScoord"+ind,"");
else text([xmax,ymin]," ","aboveleft","AScoord"+ind,"");
}
function updateCoords0() {updateCoords(0)}
function updateCoords1() {updateCoords(1)}
function updateCoords2() {updateCoords(2)}
function updateCoords3() {updateCoords(3)}
function updateCoords4() {updateCoords(4)}
function updateCoords5() {updateCoords(5)}
function updateCoords6() {updateCoords(6)}
function updateCoords7() {updateCoords(7)}
function updateCoords8() {updateCoords(8)}
function updateCoords9() {updateCoords(9)}
ASfn = [function() {updatePicture(0)},
function() {updatePicture(1)},
function() {updatePicture(2)},
function() {updatePicture(3)},
function() {updatePicture(4)},
function() {updatePicture(5)},
function() {updatePicture(6)},
function() {updatePicture(7)},
function() {updatePicture(8)},
function() {updatePicture(9)}];
ASupdateCoords = [function() {updateCoords(0)},
function() {updateCoords(1)},
function() {updateCoords(2)},
function() {updateCoords(3)},
function() {updateCoords(4)},
function() {updateCoords(5)},
function() {updateCoords(6)},
function() {updateCoords(7)},
function() {updateCoords(8)},
function() {updateCoords(9)}];
/************* my code goes here *********************/
Story.prototype.OLDSVGrefreshTiddler=Story.prototype.refreshTiddler;
Story.prototype.refreshTiddler=function(title,template,force,customFields,defaultText)
{
var k=this.OLDSVGrefreshTiddler(title, template, force,
customFields,defaultText);
drawPictures();
return k;
}
//}}}
/***
|Name:|SelectThemePlugin|
|Description:|Lets you easily switch theme and palette|
|Version:|1.0 ($Rev: 3646 $)|
|Date:|$Date: 2008-02-27 02:34:38 +1000 (Wed, 27 Feb 2008) $|
|Source:|http://mptw.tiddlyspot.com/#SelectThemePlugin|
|Author:|Simon Baird <simon.baird@gmail.com>|
|License:|http://mptw.tiddlyspot.com/#TheBSDLicense|
!Notes
* Borrows largely from ThemeSwitcherPlugin by Martin Budden http://www.martinswiki.com/#ThemeSwitcherPlugin
* Theme is cookie based. But set a default by setting config.options.txtTheme in MptwConfigPlugin (for example)
* Palette is not cookie based. It actually overwrites your ColorPalette tiddler when you select a palette, so beware.
!Usage
* {{{<<selectTheme>>}}} makes a dropdown selector
* {{{<<selectPalette>>}}} makes a dropdown selector
* {{{<<applyTheme>>}}} applies the current tiddler as a theme
* {{{<<applyPalette>>}}} applies the current tiddler as a palette
* {{{<<applyTheme TiddlerName>>}}} applies TiddlerName as a theme
* {{{<<applyPalette TiddlerName>>}}} applies TiddlerName as a palette
***/
//{{{
config.macros.selectTheme = {
label: {
selectTheme:"select theme",
selectPalette:"select palette"
},
prompt: {
selectTheme:"Select the current theme",
selectPalette:"Select the current palette"
},
tags: {
selectTheme:'systemTheme',
selectPalette:'systemPalette'
}
};
config.macros.selectTheme.handler = function(place,macroName)
{
var btn = createTiddlyButton(place,this.label[macroName],this.prompt[macroName],this.onClick);
// want to handle palettes and themes with same code. use mode attribute to distinguish
btn.setAttribute('mode',macroName);
};
config.macros.selectTheme.onClick = function(ev)
{
var e = ev ? ev : window.event;
var popup = Popup.create(this);
var mode = this.getAttribute('mode');
var tiddlers = store.getTaggedTiddlers(config.macros.selectTheme.tags[mode]);
// for default
if (mode == "selectPalette") {
var btn = createTiddlyButton(createTiddlyElement(popup,'li'),"(default)","default color palette",config.macros.selectTheme.onClickTheme);
btn.setAttribute('theme',"(default)");
btn.setAttribute('mode',mode);
}
for(var i=0; i<tiddlers.length; i++) {
var t = tiddlers[i].title;
var name = store.getTiddlerSlice(t,'Name');
var desc = store.getTiddlerSlice(t,'Description');
var btn = createTiddlyButton(createTiddlyElement(popup,'li'),name ? name : title,desc ? desc : config.macros.selectTheme.label['mode'],config.macros.selectTheme.onClickTheme);
btn.setAttribute('theme',t);
btn.setAttribute('mode',mode);
}
Popup.show();
return stopEvent(e);
};
config.macros.selectTheme.onClickTheme = function(ev)
{
var mode = this.getAttribute('mode');
var theme = this.getAttribute('theme');
if (mode == 'selectTheme')
story.switchTheme(theme);
else // selectPalette
config.macros.selectTheme.updatePalette(theme);
return false;
};
config.macros.selectTheme.updatePalette = function(title)
{
if (title != "") {
store.deleteTiddler("ColorPalette");
if (title != "(default)")
store.saveTiddler("ColorPalette","ColorPalette",store.getTiddlerText(title),
config.options.txtUserName,undefined,"");
refreshAll();
if(config.options.chkAutoSave)
saveChanges(true);
}
};
config.macros.applyTheme = {
label: "apply",
prompt: "apply this theme or palette" // i'm lazy
};
config.macros.applyTheme.handler = function(place,macroName,params,wikifier,paramString,tiddler) {
var useTiddler = params[0] ? params[0] : tiddler.title;
var btn = createTiddlyButton(place,this.label,this.prompt,config.macros.selectTheme.onClickTheme);
btn.setAttribute('theme',useTiddler);
btn.setAttribute('mode',macroName=="applyTheme"?"selectTheme":"selectPalette"); // a bit untidy here
}
config.macros.selectPalette = config.macros.selectTheme;
config.macros.applyPalette = config.macros.applyTheme;
config.macros.refreshAll = { handler: function(place,macroName,params,wikifier,paramString,tiddler) {
createTiddlyButton(place,"refresh","refresh layout and styles",function() { refreshAll(); });
}};
//}}}
/***
|Name|SetIconPlugin|
|Source|http://www.TiddlyTools.com/#SetIconPlugin|
|Documentation|http://www.TiddlyTools.com/#SetIconPluginInfo|
|Version|1.8.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.3|
|Type|plugin|
|Requires||
|Overrides||
|Options|##Configuration|
|Description|add an image to a toolbar, macro, or slider link|
!!!!!Documentation
>see [[SetIconPluginInfo]]
!!!!!Configuration
<<<
<<option chkIconsShowImage>> show images on links
<<option chkIconsShowText>> include link text with images
default image style: {{stretch{<<option txtIconsCSS>>}}}
<<<
!!!!!Revisions
<<<
2008.05.11 [1.8.0] added optional 'notext' value for iconpos to force text to be hidden for specific links
| see [[SetIconPluginInfo]] for additional revision details |
2008.05.09 [1.0.0] initial release (as inline script)
<<<
!!!!!Code
***/
//{{{
version.extensions.setIcon= {major: 1, minor: 8, revision: 0, date: new Date(2008,5,11)};
if (config.options.chkIconsShowImage===undefined)
config.options.chkIconsShowImage=true;
if (config.options.chkIconsShowText===undefined)
config.options.chkIconsShowText=true;
if (config.options.txtIconsCSS===undefined)
config.options.txtIconsCSS="vertical-align:middle;width:auto;height:auto";
config.macros.setIcon = {
handler: function(place,macroName,params,wikifier,paramString,tiddler) {
if (!config.options.chkIconsShowImage) return; // text-only - do nothing
if (!params[0]) return; // no image src specified - do nothing
// find nearest link element
var btn=place.lastChild; // look for sibling link
while (btn && btn.nodeName!="A") btn=btn.previousSibling;
if (!btn) { // look for child link
var links=place.getElementsByTagName("A");
if (links.length) btn=links[links.length-1];
}
if (!btn) { // look for parent link
var btn=place.parentNode.lastChild;
while (btn && btn.nodeName!="A") btn=btn.previousSibling;
}
if (!btn) { // look for cousin link
var links=place.parentNode.getElementsByTagName("A");
if (links.length) btn=links[links.length-1];
}
if (!btn) return; // can't find a link - do nothing
// set icon and command text/tip
var txt=btn.innerHTML;
var src=params[0]; // default to direct URL
if (config.macros.attach && config.macros.attach.isAttachment(src))
src=config.macros.attach.getAttachment(src); // retrieve attachment (if any)
var css=params[1]; if (!css||!css.length) css=config.options.txtIconsCSS;
var after=params[2]&¶ms[2].toUpperCase()=="RIGHT";
var notext=params[2]&¶ms[2].toUpperCase()=="NOTEXT";
btn.innerHTML="<img src='"+src+"' style='"+css+"'>";
if (config.options.chkIconsShowText && !notext)
btn.innerHTML=after?txt+btn.innerHTML:btn.innerHTML+txt;
else
btn.title=txt.toUpperCase()+": "+btn.title; // add text to tooltip
// adjust nested slider button text/tip
if (btn.getAttribute("closedtext")!=null) {
btn.setAttribute("closedtext",btn.innerHTML);
btn.setAttribute("openedtext",btn.innerHTML);
if (!config.options.chkIconsShowText || notext) {
btn.setAttribute("closedtip",txt.toUpperCase()+": "+btn.getAttribute("closedtip"));
btn.setAttribute("openedtip",txt.toUpperCase()+": "+btn.getAttribute("openedtip"));
}
}
}
};
//}}}
/***
|Name|SetIconPlugin|
|Source|http://www.TiddlyTools.com/#SetIconPlugin|
|Documentation|http://www.TiddlyTools.com/#SetIconPluginInfo|
|Version|1.8.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.3|
|Type|documentation|
|Requires||
|Overrides||
|Options|##Configuration|
|Description|documentation for SetIconPluginInfo|
!!!!!Syntax
<<<
{{{
<<setIcon image style iconpos>>
}}}
where:
*''image''<br>is a tiddlername for an attached image or a URL for an external image
*''style''<br>(optional) is CSS style attributes applied to the image (default="vertical-align:middle;width:auto;height:auto")
*''iconpos''<br>(optional) indicates the placement of the image relative to the link text. Use keywords: ''left'', ''right'' or ''notext'' (default=''left'', i.e., the text follows the image). ''notext'' hides the link text, even if the global option (see Configuration section, below) is set to display the link text along with image. //Note: when specifying the non-default //''right''// or //''notext''// value, you can use "" as a placeholder for the ''style'' parameter to apply the standard CSS styles)//
<<<
!!!!!Usage
<<<
First, create a link element using any of:
* ''links:''<br> """[[TiddlerName]]""" or """[[text|TiddlerName]]""" or """[[text|URL]]"""
* ''macros that generate links:''<br> """<<toolbar ...>>""", """<<slider ...>>""", """<<saveChanges>>""", etc.
* ''inline sliders:'' (using NestedSlidersPlugin)<br> """+++[sliderlabel]...==="""
* '''onclick' scripts:'' (using InlineJavascriptPlugin)<br> """<script label="...">...</script>"""
* ''~HTML-based links:''<br> """<html><a href="...">...</a></html>"""
* ''transcluded links:'' (where the output of the specified ~TiddlerName contains a link)<br> """<<tiddler TiddlerName>>"""
Then, ''embed the """<<setIcon>>""" macro immediately following the generated link''. The macro looks for the last rendered //sibling// link element that occurs within the same DOM container and adds the specified image to that link. It is important to note that the macro does not initially look within the //child// DOM elements of the current container. This is necessary so that 'sliderPanel' content created by the """<<slider>>""" macro can be skipped over, allowing the correct 'sliderButton' link element to be located.
When you use the """<<tiddler>>""" macro to transclude content containing a link, or you directly embed a link using HTML syntax, the resulting link element will //always// be rendered within a //child// DOM element container. However, the """<<setIcon>>""" macro only looks within //child// DOM elements when no //sibling// link elements are found within the current DOM container. In order to ensure that the """<<setIcon>>""" macro will not inadvertently find a sibling link element, you will need to isolate the child DOM element container link along with the associated """<<setIcon>>""" macro that follows it by enclosing the both elements within a surrounding SPAN 'class wrapper' element, like this:
{{{
{{span{<<tiddler SomeTranscludedLink>><<setIcon ...>>}}}
{{span{<html><a href="...">...</a></html><<setIcon ...>>}}}
}}}
This same technique should also be applied for any other macros that may generate output that is nested within their own containing DOM elements. Similarly, in addition to """<<tiddler>>""" and ~HTML-based content, link elements that are defined directly within a ViewTemplate or EditTemplate definition using """<span macro='...'></span>""" are also rendered within their own DOM element containers. In order to ensure that the associated """<span macro='setIcon ...'></span>""" macro will locate the correct template-defined link element, it should be inserted //within// the span that invokes the link-generating macro, like this:
{{{
<span macro='...'><span macro='setIcon ...'></span></span>
}}}
or, your can surround the paired link+icon sequence in an enclosing span, like this:
{{{
<span><span macro='...'></span><span macro='setIcon ...'></span></span>
}}}
so that the span containing the link element is a //cousin// (i.e., a //child// of the //parent// container) of the span that invokes the setIcon macro.
''In general, whether the link element is rendered in tiddler content or directly from a template, if you are uncertain when an 'isolation span' is needed, you can always choose to surround every link+icon sequence within a enclosing span, regardless of the type of link content being rendered.''
<<<
!!!!!Examples
<<<
''~TiddlyLink:'' [[About]]<<setIcon information.png>>
{{{
[[About]]<<setIcon information.png>>
}}}
''toolbar command:'' <<toolbar jump>><<setIcon page_go.png>>
{{{
in tiddler content:
<<toolbar jump>><<setIcon page_go.png>>
in template definitions:
<span class='toolbar' macro='toolbar jump'><span macro='setIcon page_go.png'></span></span>
}}}
''slider macro:''<<slider "" PluginManager Plugins "view installed plugin status">><<setIcon cog.png>>
{{{
in tiddler content:
<<slider "" PluginManager Plugins "view installed plugin status">><<setIcon cog.png>>
in template definitions:
<span macro='slider ...'><span macro='setIcon page_go.png'></span></span>
}}}
''nested (inline) slider:'' +++[settings]<<list filter [tag[settings]]>>===<<setIcon wrench.png>>
{{{
+++[settings]
<<list filter [tag[settings]]>>
===<<setIcon wrench.png>>
}}}
''onclick script:'' <script label="print document">window.print();</script><<setIcon printer.png>>
{{{
<script label="print document">
window.print();
</script><<setIcon printer.png>>
}}}
''tiddler macro:'' {{span{<<tiddler SiteUrl>><<setIcon exclamation.png>>}}}
{{{
in tiddler content:
{{span{<<tiddler SiteUrl>><<setIcon exclamation.png>>}}}
in template definitions:
<span macro='tiddler ...'><span macro='setIcon exclamation.png'></span></span>
}}}
''HTML link:'' {{span{<html><a href="http://www.TiddlyWiki.com">TiddlyWiki.com</a></html><<setIcon server_go.png>>}}}
{{{
in tiddler content:
{{span{<html><a href="http://www.TiddlyWiki.com">TiddlyWiki.com</a></html><<setIcon server_go.png>>}}}
in template definitions:
<span><a href="http://www.TiddlyWiki.com">TiddlyWiki.com</a><span macro='setIcon server_go.png'></span></span>
}}}
''macro link:'' {{span{<<saveChanges>><<setIcon disk.png>>}}}
{{{
in tiddler content:
{{span{<<saveChanges>><<setIcon disk.png>>}}}
in template definitions:
<span macro='saveChanges'><span macro='setIcon disk.png'></span></span>
}}}
<<<
!!!!!Configuration
<<<
<<option chkIconsShowImage>> show icons on links //(unchecked=text-only)//
^^{{{<<option chkIconsShowImage>>}}}^^
<<option chkIconsShowText>> include link text with images //(unchecked=icons-only, ignored if no icons displayed)//
^^{{{<<option chkIconsShowText>>}}}^^
default image style: {{stretch{<<option txtIconsCSS>>}}}
^^{{{<<option txtIconsCSS>>}}}^^
<<<
!!!!!Revisions
<<<
2008.05.11 [1.8.0] added optional 'notext' value for iconpos to force text to be hidden for specific links
2008.05.11 [1.7.0] support use within template definitions by looking for nearest link using: siblings, children, parents, or cousins. Also, major documentation re-write with improved examples
2008.05.11 [1.6.0] added optional iconpos param to control icon placement ("left" or "right", default="left")
2008.05.10 [1.5.0] converted to plugin/macro and reduced code size by moving documentation into SetIconPluginInfo
2008.05.10 [1.4.0] handle links contained in {{{<<tiddler>>}}} and {{{<html>...</html}}}
2008.05.10 [1.3.0] added support for setting styles on images
2008.05.09 [1.2.0] handle links created by TiddlyLinks, sliders, and nested sliders syntax
2008.05.09 [1.1.0] added support for external URLs and options for displaying text with images
2008.05.09 [1.0.0] initial release (as inline script)
<<<
<<search>><<closeAll>><<permaview>><<newTiddler>><<newJournal "DD MMM YYYY" "journal">><<saveChanges>><<slider chkSliderOptionsPanel OptionsPanel "options »" "Change TiddlyWiki advanced options">>
<<slider chkSliderCalendarPanel CalendarPanel "calendar »" "Month calendar">>
<<slider chkSliderMicroCalc MicroCalc "calc »" "Calculator">>
<<slider chkSliderDicas Dicas "dicas »" "Dicas">>
name <<option txtUserName>>
<<slider chkSliderTabsPanel TabsPanel "tabs »" "Tabs with tiddler lists">>
Dicas para utilizar o AsciiMathML.
Colocar as equações entre sinais de aspas para trás{{{`}}}.
Assim são obtidos:
| x^2 | `x^2` |
| x_12 | `x_12` |
| sum_(i=1)^(oo) (1)/(i!) | `sum_(i=1)^(oo) (1)/(i!)` |
| [(a,b),(c,...)] | `[(a,b),(c,...)]` |
Dicas para escrever no Wiki.
Com {{{//}}} //itálico//.
Com {{{''}}} ''negrito''.
Com {{{[[}}} [[Hiperlinks]]
Com {{{----}}} traço horizontal
----
Com {{{!, !!, !!!}}}
!Titulos e
!!Subtitulos e
!!!Subsubtitulos
Com {{{*}}} itens
* um
* dois
* três
** tres ponto um
Com {{{#}}} itens numerados
# a
# b
# c
Dicas para utilizar o AsciiSVG.
CT-200 Fundamentos de Linguagens Formais e Automata
<<tabs txtMoreTab "Tags" "All Tags" TabAllTags "Miss" "Missing tiddlers" TabMoreMissing "Orph" "Orphaned tiddlers" TabMoreOrphans "Shad" "Shadowed tiddlers" TabMoreShadowed>>
<<allTags excludeLists [a-z]>>
/***
|''Name:''|TableSortingPlugin|
|''Description:''|Dynamically sort tables by clicking on column headers|
|''Author:''|Saq Imtiaz ( lewcid@gmail.com )|
|''Source:''|http://tw.lewcid.org/#TableSortingPlugin|
|''Code Repository:''|http://tw.lewcid.org/svn/plugins|
|''Version:''|2.02|
|''Date:''|25-01-2008|
|''License:''|[[Creative Commons Attribution-ShareAlike 3.0 License|http://creativecommons.org/licenses/by-sa/3.0/]]|
|''~CoreVersion:''|2.2.3|
!!Usage:
* Make sure your table has a header row
** {{{|Name|Phone Number|Address|h}}}<br> Note the /h/ that denote a header row
* Give the table a class of 'sortable'
** {{{
|sortable|k
|Name|Phone Number|Address|h
}}}<br>Note the /k/ that denotes a class name being assigned to the table.
* To disallow sorting by a column, place {{{<<nosort>>}}} in it's header
* To automatically sort a table by a column, place {{{<<autosort>>}}} in the header for that column
** Or to sort automatically but in reverse order, use {{{<<autosort reverse>>}}}
!!Example:
|sortable|k
|Name |Salary |Extension |Performance |File Size |Start date |h
|ZBloggs, Fred |$12000.00 |1353 |+1.2 |74.2Kb |Aug 19, 2003 21:34:00 |
|ABloggs, Fred |$12000.00 |1353 |1.2 |3350b |09/18/2003 |
|CBloggs, Fred |$12000 |1353 |1.200 |55.2Kb |August 18, 2003 |
|DBloggs, Fred |$12000.00 |1353 |1.2 |2100b |07/18/2003 |
|Bloggs, Fred |$12000.00 |1353 |01.20 |6.156Mb |08/17/2003 05:43 |
|Turvey, Kevin |$191200.00 |2342 |-33 |1b |02/05/1979 |
|Mbogo, Arnold |$32010.12 |2755 |-21.673 |1.2Gb |09/08/1998 |
|Shakespeare, Bill |£122000.00|3211 |6 |33.22Gb |12/11/1961 |
|Shakespeare, Hamlet |£9000 |9005 |-8 |3Gb |01/01/2002 |
|Fitz, Marvin |€3300.30 |5554 |+5 |4Kb |05/22/1995 |
***/
// /%
//!BEGIN-PLUGIN-CODE
config.tableSorting = {
darrow: "\u2193",
uarrow: "\u2191",
getText : function (o) {
var p = o.cells[SORT_INDEX];
return p.innerText || p.textContent || '';
},
sortTable : function (o,rev) {
SORT_INDEX = o.getAttribute("index");
var c = config.tableSorting;
var T = findRelated(o.parentNode,"TABLE");
if(T.tBodies[0].rows.length<=1)
return;
var itm = "";
var i = 0;
while (itm == "" && i < T.tBodies[0].rows.length) {
itm = c.getText(T.tBodies[0].rows[i]).trim();
i++;
}
if (itm == "")
return;
var r = [];
var S = o.getElementsByTagName("span")[0];
c.fn = c.sortAlpha;
if(!isNaN(Date.parse(itm)))
c.fn = c.sortDate;
else if(itm.match(/^[$|£|€|\+|\-]{0,1}\d*\.{0,1}\d+$/))
c.fn = c.sortNumber;
else if(itm.match(/^\d*\.{0,1}\d+[K|M|G]{0,1}b$/))
c.fn = c.sortFile;
for(i=0; i<T.tBodies[0].rows.length; i++) {
r[i]=T.tBodies[0].rows[i];
}
r.sort(c.reSort);
if(S.firstChild.nodeValue==c.darrow || rev) {
r.reverse();
S.firstChild.nodeValue=c.uarrow;
}
else
S.firstChild.nodeValue=c.darrow;
var thead = T.getElementsByTagName('thead')[0];
var headers = thead.rows[thead.rows.length-1].cells;
for(var k=0; k<headers.length; k++) {
if(!hasClass(headers[k],"nosort"))
addClass(headers[k].getElementsByTagName("span")[0],"hidden");
}
removeClass(S,"hidden");
for(i=0; i<r.length; i++) {
T.tBodies[0].appendChild(r[i]);
c.stripe(r[i],i);
for(var j=0; j<r[i].cells.length;j++){
removeClass(r[i].cells[j],"sortedCol");
}
addClass(r[i].cells[SORT_INDEX],"sortedCol");
}
},
stripe : function (e,i){
var cl = ["oddRow","evenRow"];
i&1? cl.reverse() : cl;
removeClass(e,cl[1]);
addClass(e,cl[0]);
},
sortNumber : function(v) {
var x = parseFloat(this.getText(v).replace(/[^0-9.-]/g,''));
return isNaN(x)? 0: x;
},
sortDate : function(v) {
return Date.parse(this.getText(v));
},
sortAlpha : function(v) {
return this.getText(v).toLowerCase();
},
sortFile : function(v) {
var j, q = config.messages.sizeTemplates, s = this.getText(v);
for (var i=0; i<q.length; i++) {
if ((j = s.toLowerCase().indexOf(q[i].template.replace("%0\u00a0","").toLowerCase())) != -1)
return q[i].unit * s.substr(0,j);
}
return parseFloat(s);
},
reSort : function(a,b){
var c = config.tableSorting;
var aa = c.fn(a);
var bb = c.fn(b);
return ((aa==bb)? 0 : ((aa<bb)? -1:1));
}
};
Story.prototype.tSort_refreshTiddler = Story.prototype.refreshTiddler;
Story.prototype.refreshTiddler = function(title,template,force,customFields,defaultText){
var elem = this.tSort_refreshTiddler.apply(this,arguments);
if(elem){
var tables = elem.getElementsByTagName("TABLE");
var c = config.tableSorting;
for(var i=0; i<tables.length; i++){
if(hasClass(tables[i],"sortable")){
var x = null, rev, table = tables[i], thead = table.getElementsByTagName('thead')[0], headers = thead.rows[thead.rows.length-1].cells;
for (var j=0; j<headers.length; j++){
var h = headers[j];
if (hasClass(h,"nosort"))
continue;
h.setAttribute("index",j);
h.onclick = function(){c.sortTable(this); return false;};
h.ondblclick = stopEvent;
if(h.getElementsByTagName("span").length == 0)
createTiddlyElement(h,"span",null,"hidden",c.uarrow);
if(!x && hasClass(h,"autosort")) {
x = j;
rev = hasClass(h,"reverse");
}
}
if(x)
c.sortTable(headers[x],rev);
}
}
}
return elem;
};
setStylesheet("table.sortable span.hidden {visibility:hidden;}\n"+
"table.sortable thead {cursor:pointer;}\n"+
"table.sortable .nosort {cursor:default;}\n"+
"table.sortable td.sortedCol {background:#ffc;}","TableSortingPluginStyles");
function stopEvent(e){
var ev = e? e : window.event;
ev.cancelBubble = true;
if (ev.stopPropagation) ev.stopPropagation();
return false;
}
config.macros.nosort={
handler : function(place){
addClass(place,"nosort");
}
};
config.macros.autosort={
handler : function(place,m,p,w,pS){
addClass(place,"autosort"+" "+pS);
}
};
//!END-PLUGIN-CODE
// %/
<<tabs txtMainTab "Timeline" "Timeline" TabTimeline "All" "All tiddlers" TabAll "Tags" "All tags" TabTags "More" "More lists" TabMore>>
/***
|Name:|TagglyTaggingPlugin|
|Description:|tagglyTagging macro is a replacement for the builtin tagging macro in your ViewTemplate|
|Version:|3.1 ($Rev: 5655 $)|
|Date:|$Date: 2008-06-18 23:50:30 +1000 (Wed, 18 Jun 2008) $|
|Source:|http://mptw.tiddlyspot.com/#TagglyTaggingPlugin|
|Author:|Simon Baird <simon.baird@gmail.com>|
|License:|http://mptw.tiddlyspot.com/#TheBSDLicense|
!Notes
See http://mptw.tiddlyspot.com/#TagglyTagging
***/
//{{{
config.taggly = {
// for translations
lingo: {
labels: {
asc: "\u2191", // down arrow
desc: "\u2193", // up arrow
title: "title",
modified: "modified",
created: "created",
show: "+",
hide: "-",
normal: "normal",
group: "group",
commas: "commas",
sitemap: "sitemap",
numCols: "cols\u00b1", // plus minus sign
label: "Tagged as '%0':",
excerpts: "excerpts",
descr: "descr",
slices: "slices",
contents: "contents",
sliders: "sliders",
noexcerpts: "title only"
},
tooltips: {
title: "Click to sort by title",
modified: "Click to sort by modified date",
created: "Click to sort by created date",
show: "Click to show tagging list",
hide: "Click to hide tagging list",
normal: "Click to show a normal ungrouped list",
group: "Click to show list grouped by tag",
sitemap: "Click to show a sitemap style list",
commas: "Click to show a comma separated list",
numCols: "Click to change number of columns",
excerpts: "Click to show excerpts",
descr: "Click to show the description slice",
slices: "Click to show all slices",
contents: "Click to show entire tiddler contents",
sliders: "Click to show tiddler contents in sliders",
noexcerpts: "Click to show entire title only"
},
tooDeepMessage: "* //sitemap too deep...//"
},
config: {
showTaggingCounts: true,
listOpts: {
// the first one will be the default
sortBy: ["title","modified","created"],
sortOrder: ["asc","desc"],
hideState: ["show","hide"],
listMode: ["normal","group","sitemap","commas"],
numCols: ["1","2","3","4","5","6"],
excerpts: ["noexcerpts","excerpts","descr","slices","contents","sliders"]
},
valuePrefix: "taggly.",
excludeTags: ["excludeLists","excludeTagging"],
excerptSize: 50,
excerptMarker: "/%"+"%/",
siteMapDepthLimit: 25
},
getTagglyOpt: function(title,opt) {
var val = store.getValue(title,this.config.valuePrefix+opt);
return val ? val : this.config.listOpts[opt][0];
},
setTagglyOpt: function(title,opt,value) {
if (!store.tiddlerExists(title))
// create it silently
store.saveTiddler(title,title,config.views.editor.defaultText.format([title]),config.options.txtUserName,new Date(),"");
// if value is default then remove it to save space
return store.setValue(title,
this.config.valuePrefix+opt,
value == this.config.listOpts[opt][0] ? null : value);
},
getNextValue: function(title,opt) {
var current = this.getTagglyOpt(title,opt);
var pos = this.config.listOpts[opt].indexOf(current);
// a little usability enhancement. actually it doesn't work right for grouped or sitemap
var limit = (opt == "numCols" ? store.getTaggedTiddlers(title).length : this.config.listOpts[opt].length);
var newPos = (pos + 1) % limit;
return this.config.listOpts[opt][newPos];
},
toggleTagglyOpt: function(title,opt) {
var newVal = this.getNextValue(title,opt);
this.setTagglyOpt(title,opt,newVal);
},
createListControl: function(place,title,type) {
var lingo = config.taggly.lingo;
var label;
var tooltip;
var onclick;
if ((type == "title" || type == "modified" || type == "created")) {
// "special" controls. a little tricky. derived from sortOrder and sortBy
label = lingo.labels[type];
tooltip = lingo.tooltips[type];
if (this.getTagglyOpt(title,"sortBy") == type) {
label += lingo.labels[this.getTagglyOpt(title,"sortOrder")];
onclick = function() {
config.taggly.toggleTagglyOpt(title,"sortOrder");
return false;
}
}
else {
onclick = function() {
config.taggly.setTagglyOpt(title,"sortBy",type);
config.taggly.setTagglyOpt(title,"sortOrder",config.taggly.config.listOpts.sortOrder[0]);
return false;
}
}
}
else {
// "regular" controls, nice and simple
label = lingo.labels[type == "numCols" ? type : this.getNextValue(title,type)];
tooltip = lingo.tooltips[type == "numCols" ? type : this.getNextValue(title,type)];
onclick = function() {
config.taggly.toggleTagglyOpt(title,type);
return false;
}
}
// hide button because commas don't have columns
if (!(this.getTagglyOpt(title,"listMode") == "commas" && type == "numCols"))
createTiddlyButton(place,label,tooltip,onclick,type == "hideState" ? "hidebutton" : "button");
},
makeColumns: function(orig,numCols) {
var listSize = orig.length;
var colSize = listSize/numCols;
var remainder = listSize % numCols;
var upperColsize = colSize;
var lowerColsize = colSize;
if (colSize != Math.floor(colSize)) {
// it's not an exact fit so..
upperColsize = Math.floor(colSize) + 1;
lowerColsize = Math.floor(colSize);
}
var output = [];
var c = 0;
for (var j=0;j<numCols;j++) {
var singleCol = [];
var thisSize = j < remainder ? upperColsize : lowerColsize;
for (var i=0;i<thisSize;i++)
singleCol.push(orig[c++]);
output.push(singleCol);
}
return output;
},
drawTable: function(place,columns,theClass) {
var newTable = createTiddlyElement(place,"table",null,theClass);
var newTbody = createTiddlyElement(newTable,"tbody");
var newTr = createTiddlyElement(newTbody,"tr");
for (var j=0;j<columns.length;j++) {
var colOutput = "";
for (var i=0;i<columns[j].length;i++)
colOutput += columns[j][i];
var newTd = createTiddlyElement(newTr,"td",null,"tagglyTagging"); // todo should not need this class
wikify(colOutput,newTd);
}
return newTable;
},
createTagglyList: function(place,title) {
switch(this.getTagglyOpt(title,"listMode")) {
case "group": return this.createTagglyListGrouped(place,title); break;
case "normal": return this.createTagglyListNormal(place,title,false); break;
case "commas": return this.createTagglyListNormal(place,title,true); break;
case "sitemap":return this.createTagglyListSiteMap(place,title); break;
}
},
getTaggingCount: function(title) {
// thanks to Doug Edmunds
if (this.config.showTaggingCounts) {
var tagCount = store.getTaggedTiddlers(title).length;
if (tagCount > 0)
return " ("+tagCount+")";
}
return "";
},
getExcerpt: function(inTiddlerTitle,title,indent) {
if (!indent)
indent = 1;
var displayMode = this.getTagglyOpt(inTiddlerTitle,"excerpts");
var t = store.getTiddler(title);
if (t && displayMode == "excerpts") {
var text = t.text.replace(/\n/," ");
var marker = text.indexOf(this.config.excerptMarker);
if (marker != -1) {
return " {{excerpt{<nowiki>" + text.substr(0,marker) + "</nowiki>}}}";
}
else if (text.length < this.config.excerptSize) {
return " {{excerpt{<nowiki>" + t.text + "</nowiki>}}}";
}
else {
return " {{excerpt{<nowiki>" + t.text.substr(0,this.config.excerptSize) + "..." + "</nowiki>}}}";
}
}
else if (t && displayMode == "contents") {
return "\n{{contents indent"+indent+"{\n" + t.text + "\n}}}";
}
else if (t && displayMode == "sliders") {
return "<slider slide>\n{{contents{\n" + t.text + "\n}}}\n</slider>";
}
else if (t && displayMode == "descr") {
var descr = store.getTiddlerSlice(title,'Description');
return descr ? " {{excerpt{" + descr + "}}}" : "";
}
else if (t && displayMode == "slices") {
var result = "";
var slices = store.calcAllSlices(title);
for (var s in slices)
result += "|%0|<nowiki>%1</nowiki>|\n".format([s,slices[s]]);
return result ? "\n{{excerpt excerptIndent{\n" + result + "}}}" : "";
}
return "";
},
notHidden: function(t,inTiddler) {
if (typeof t == "string")
t = store.getTiddler(t);
return (!t || !t.tags.containsAny(this.config.excludeTags) ||
(inTiddler && this.config.excludeTags.contains(inTiddler)));
},
// this is for normal and commas mode
createTagglyListNormal: function(place,title,useCommas) {
var list = store.getTaggedTiddlers(title,this.getTagglyOpt(title,"sortBy"));
if (this.getTagglyOpt(title,"sortOrder") == "desc")
list = list.reverse();
var output = [];
var first = true;
for (var i=0;i<list.length;i++) {
if (this.notHidden(list[i],title)) {
var countString = this.getTaggingCount(list[i].title);
var excerpt = this.getExcerpt(title,list[i].title);
if (useCommas)
output.push((first ? "" : ", ") + "[[" + list[i].title + "]]" + countString + excerpt);
else
output.push("*[[" + list[i].title + "]]" + countString + excerpt + "\n");
first = false;
}
}
return this.drawTable(place,
this.makeColumns(output,useCommas ? 1 : parseInt(this.getTagglyOpt(title,"numCols"))),
useCommas ? "commas" : "normal");
},
// this is for the "grouped" mode
createTagglyListGrouped: function(place,title) {
var sortBy = this.getTagglyOpt(title,"sortBy");
var sortOrder = this.getTagglyOpt(title,"sortOrder");
var list = store.getTaggedTiddlers(title,sortBy);
if (sortOrder == "desc")
list = list.reverse();
var leftOvers = []
for (var i=0;i<list.length;i++)
leftOvers.push(list[i].title);
var allTagsHolder = {};
for (var i=0;i<list.length;i++) {
for (var j=0;j<list[i].tags.length;j++) {
if (list[i].tags[j] != title) { // not this tiddler
if (this.notHidden(list[i].tags[j],title)) {
if (!allTagsHolder[list[i].tags[j]])
allTagsHolder[list[i].tags[j]] = "";
if (this.notHidden(list[i],title)) {
allTagsHolder[list[i].tags[j]] += "**[["+list[i].title+"]]"
+ this.getTaggingCount(list[i].title) + this.getExcerpt(title,list[i].title) + "\n";
leftOvers.setItem(list[i].title,-1); // remove from leftovers. at the end it will contain the leftovers
}
}
}
}
}
var allTags = [];
for (var t in allTagsHolder)
allTags.push(t);
var sortHelper = function(a,b) {
if (a == b) return 0;
if (a < b) return -1;
return 1;
};
allTags.sort(function(a,b) {
var tidA = store.getTiddler(a);
var tidB = store.getTiddler(b);
if (sortBy == "title") return sortHelper(a,b);
else if (!tidA && !tidB) return 0;
else if (!tidA) return -1;
else if (!tidB) return +1;
else return sortHelper(tidA[sortBy],tidB[sortBy]);
});
var leftOverOutput = "";
for (var i=0;i<leftOvers.length;i++)
if (this.notHidden(leftOvers[i],title))
leftOverOutput += "*[["+leftOvers[i]+"]]" + this.getTaggingCount(leftOvers[i]) + this.getExcerpt(title,leftOvers[i]) + "\n";
var output = [];
if (sortOrder == "desc")
allTags.reverse();
else if (leftOverOutput != "")
// leftovers first...
output.push(leftOverOutput);
for (var i=0;i<allTags.length;i++)
if (allTagsHolder[allTags[i]] != "")
output.push("*[["+allTags[i]+"]]" + this.getTaggingCount(allTags[i]) + this.getExcerpt(title,allTags[i]) + "\n" + allTagsHolder[allTags[i]]);
if (sortOrder == "desc" && leftOverOutput != "")
// leftovers last...
output.push(leftOverOutput);
return this.drawTable(place,
this.makeColumns(output,parseInt(this.getTagglyOpt(title,"numCols"))),
"grouped");
},
// used to build site map
treeTraverse: function(title,depth,sortBy,sortOrder) {
var list = store.getTaggedTiddlers(title,sortBy);
if (sortOrder == "desc")
list.reverse();
var indent = "";
for (var j=0;j<depth;j++)
indent += "*"
var childOutput = "";
if (depth > this.config.siteMapDepthLimit)
childOutput += indent + this.lingo.tooDeepMessage;
else
for (var i=0;i<list.length;i++)
if (list[i].title != title)
if (this.notHidden(list[i].title,this.config.inTiddler))
childOutput += this.treeTraverse(list[i].title,depth+1,sortBy,sortOrder);
if (depth == 0)
return childOutput;
else
return indent + "[["+title+"]]" + this.getTaggingCount(title) + this.getExcerpt(this.config.inTiddler,title,depth) + "\n" + childOutput;
},
// this if for the site map mode
createTagglyListSiteMap: function(place,title) {
this.config.inTiddler = title; // nasty. should pass it in to traverse probably
var output = this.treeTraverse(title,0,this.getTagglyOpt(title,"sortBy"),this.getTagglyOpt(title,"sortOrder"));
return this.drawTable(place,
this.makeColumns(output.split(/(?=^\*\[)/m),parseInt(this.getTagglyOpt(title,"numCols"))), // regexp magic
"sitemap"
);
},
macros: {
tagglyTagging: {
handler: function (place,macroName,params,wikifier,paramString,tiddler) {
var refreshContainer = createTiddlyElement(place,"div");
// do some refresh magic to make it keep the list fresh - thanks Saq
refreshContainer.setAttribute("refresh","macro");
refreshContainer.setAttribute("macroName",macroName);
if (params[0])
refreshContainer.setAttribute("title",params[0]);
else {
refreshContainer.setAttribute("title",tiddler.title);
}
this.refresh(refreshContainer);
},
refresh: function(place) {
var title = place.getAttribute("title");
removeChildren(place);
addClass(place,"tagglyTagging");
if (store.getTaggedTiddlers(title).length > 0) {
var lingo = config.taggly.lingo;
config.taggly.createListControl(place,title,"hideState");
if (config.taggly.getTagglyOpt(title,"hideState") == "show") {
createTiddlyElement(place,"span",null,"tagglyLabel",lingo.labels.label.format([title]));
config.taggly.createListControl(place,title,"title");
config.taggly.createListControl(place,title,"modified");
config.taggly.createListControl(place,title,"created");
config.taggly.createListControl(place,title,"listMode");
config.taggly.createListControl(place,title,"excerpts");
config.taggly.createListControl(place,title,"numCols");
config.taggly.createTagglyList(place,title);
}
}
}
}
},
// todo fix these up a bit
styles: [
"/*{{{*/",
"/* created by TagglyTaggingPlugin */",
".tagglyTagging { padding-top:0.5em; }",
".tagglyTagging li.listTitle { display:none; }",
".tagglyTagging ul {",
" margin-top:0px; padding-top:0.5em; padding-left:2em;",
" margin-bottom:0px; padding-bottom:0px;",
"}",
".tagglyTagging { vertical-align: top; margin:0px; padding:0px; }",
".tagglyTagging table { margin:0px; padding:0px; }",
".tagglyTagging .button { visibility:hidden; margin-left:3px; margin-right:3px; }",
".tagglyTagging .button, .tagglyTagging .hidebutton {",
" color:[[ColorPalette::TertiaryLight]]; font-size:90%;",
" border:0px; padding-left:0.3em;padding-right:0.3em;",
"}",
".tagglyTagging .button:hover, .hidebutton:hover, ",
".tagglyTagging .button:active, .hidebutton:active {",
" border:0px; background:[[ColorPalette::TertiaryPale]]; color:[[ColorPalette::TertiaryDark]];",
"}",
".selected .tagglyTagging .button { visibility:visible; }",
".tagglyTagging .hidebutton { color:[[ColorPalette::Background]]; }",
".selected .tagglyTagging .hidebutton { color:[[ColorPalette::TertiaryLight]] }",
".tagglyLabel { color:[[ColorPalette::TertiaryMid]]; font-size:90%; }",
".tagglyTagging ul {padding-top:0px; padding-bottom:0.5em; margin-left:1em; }",
".tagglyTagging ul ul {list-style-type:disc; margin-left:-1em;}",
".tagglyTagging ul ul li {margin-left:0.5em; }",
".editLabel { font-size:90%; padding-top:0.5em; }",
".tagglyTagging .commas { padding-left:1.8em; }",
"/* not technically tagglytagging but will put them here anyway */",
".tagglyTagged li.listTitle { display:none; }",
".tagglyTagged li { display: inline; font-size:90%; }",
".tagglyTagged ul { margin:0px; padding:0px; }",
".excerpt { color:[[ColorPalette::TertiaryDark]]; }",
".excerptIndent { margin-left:4em; }",
"div.tagglyTagging table,",
"div.tagglyTagging table tr,",
"td.tagglyTagging",
" {border-style:none!important; }",
".tagglyTagging .contents { border-bottom:2px solid [[ColorPalette::TertiaryPale]]; padding:0 1em 1em 0.5em;",
" margin-bottom:0.5em; }",
".tagglyTagging .indent1 { margin-left:3em; }",
".tagglyTagging .indent2 { margin-left:4em; }",
".tagglyTagging .indent3 { margin-left:5em; }",
".tagglyTagging .indent4 { margin-left:6em; }",
".tagglyTagging .indent5 { margin-left:7em; }",
".tagglyTagging .indent6 { margin-left:8em; }",
".tagglyTagging .indent7 { margin-left:9em; }",
".tagglyTagging .indent8 { margin-left:10em; }",
".tagglyTagging .indent9 { margin-left:11em; }",
".tagglyTagging .indent10 { margin-left:12em; }",
"/*}}}*/",
""].join("\n"),
init: function() {
merge(config.macros,this.macros);
config.shadowTiddlers["TagglyTaggingStyles"] = this.styles;
store.addNotification("TagglyTaggingStyles",refreshStyles);
}
};
config.taggly.init();
//}}}
/***
InlineSlidersPlugin
By Saq Imtiaz
http://tw.lewcid.org/sandbox/#InlineSlidersPlugin
// syntax adjusted to not clash with NestedSlidersPlugin
// added + syntax to start open instead of closed
***/
//{{{
config.formatters.unshift( {
name: "inlinesliders",
// match: "\\+\\+\\+\\+|\\<slider",
match: "\\<slider",
// lookaheadRegExp: /(?:\+\+\+\+|<slider) (.*?)(?:>?)\n((?:.|\n)*?)\n(?:====|<\/slider>)/mg,
lookaheadRegExp: /(?:<slider)(\+?) (.*?)(?:>)\n((?:.|\n)*?)\n(?:<\/slider>)/mg,
handler: function(w) {
this.lookaheadRegExp.lastIndex = w.matchStart;
var lookaheadMatch = this.lookaheadRegExp.exec(w.source)
if(lookaheadMatch && lookaheadMatch.index == w.matchStart ) {
var btn = createTiddlyButton(w.output,lookaheadMatch[2] + " "+"\u00BB",lookaheadMatch[2],this.onClickSlider,"button sliderButton");
var panel = createTiddlyElement(w.output,"div",null,"sliderPanel");
panel.style.display = (lookaheadMatch[1] == '+' ? "block" : "none");
wikify(lookaheadMatch[3],panel);
w.nextMatch = lookaheadMatch.index + lookaheadMatch[0].length;
}
},
onClickSlider : function(e) {
if(!e) var e = window.event;
var n = this.nextSibling;
n.style.display = (n.style.display=="none") ? "block" : "none";
return false;
}
});
//}}}
TidIDE - TiddlyWiki Integrated Development Environment
Provides tools for authors and developers to help construct and debug the contents of their TiddlyWiki documents.
/***
|Name|TidIDEPlugin|
|Source|http://www.TiddlyTools.com/#TidIDEPlugin|
|Documentation|http://www.TiddlyTools.com/#TidIDEPluginInfo|
|Version|1.8.3|
|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||
|Options|##Configuration|
|Description|TiddlyWiki Integrated Development Environment - tools for authors and plugin writers|
~TidIDE (//prounounced "Tie Dyed"//) - ''Tid''dlyWiki ''I''ntegrated ''D''evelopment ''E''nvironment - lets you define a set of checkboxes to toggle a stack of 'tool panels' containing tools for TiddlyWiki authors to use when creating and debugging their TiddlyWiki documents. Each tool is defined by a separate tiddler, allowing you to define any convenient set of tools simply by adding/removing tiddler references from the {{{<<tidIDE...>>}}} macro call.
In addition to presenting checkboxes/tool panels that are defined in separate tiddlers, the {{{<<tidIDE>>}}} macro can invoke an optional built-in "editor panel" that presents an alternative tiddler editor to create, modify, and manage the tiddlers in your document... and, if you have also installed [[PreviewPlugin]], the editor can automatically display a ''//formatted preview//'' of the current tiddler content that is updated ''live, key-by-key'' while you edit the tiddler source.
!!!!!Documentation
>see [[TidIDEPluginInfo]]
!!!!!Configuration
<<<
Number of rows to display in text input area <<option txtTidIDEMaxEditRows>>
{{{usage: <<option txtTidIDEMaxEditRows>>}}}
^^Note: if value is not specified here, default is to use {{{<<option txtMaxEditRows>>}}} core setting (see [[AdvancedOptions]])^^
<<<
!!!!!Revisions
<<<
2008.04.24 [1.8.3] fixed 'run' button onclick handler
2007.12.21 [1.8.2] added txtTidIDEMaxEditRows option as custom override for standard core txtMaxEditRows setting
2007.09.27 [1.8.0] split preview functionality into separate stand-alone plugin (see [[PreviewPlugin]]). Moved {{{<<DOMViewer>>}}} macro definition to separate plugin (see [[DOMViewerPlugin]]). Replicated ''run'' button functionality in stand-along plugin (see [[RunTiddlerPlugin]]). Major re-write of documentation
|please see [[TidIDEPluginInfo]] for additional revision details|
2006.04.15 [0.5.0] Initial ALPHA release. Converted from inline script.
<<<
!!!!!Code
***/
// // version
//{{{
version.extensions.tidIDE = {major: 1, minor: 8, revision: 3, date: new Date(2008,4,24)};
//}}}
// // settings
//{{{
if (config.options.txtTidIDEMaxEditRows==undefined)
config.options.txtTidIDEMaxEditRows=config.options.txtMaxEditRows
//}}}
// // macro definition
//{{{
config.macros.tidIDE = {
versionMsg: "TidIDE v%0.%1.%2: ",
datetimefmt: "0MM/0DD/YYYY 0hh:0mm",
titleMsg: "Please enter a new tiddler title",
isShadowMsg: "'%0' is a shadow tiddler and cannot be removed.",
evalMsg: "Warning!! Processing '%0' as a systemConfig (plugin) tiddler may produce unexpected results! Are you sure you want to proceed?",
evalCompletedMsg: "Processing completed",
toolsDef: "<html><a href='javascript:config.macros.tidIDE.set(\"%0\",\"%1\");'>edit %1...</a></html>",
editorLabel: "TiddlerEditor"
};
config.macros.tidIDE.handler= function(place,macroName,params) {
var here=story.findContainingTiddler(place);
var selectors="";
var panels="";
var showsys=false;
var title="";
var id=""; if (here) id=here.getAttribute("tiddler").replace(/ /g,"_");
var p=params.shift();
if (!p) p="edit:here"; // default to editor if no params
var openpanels=[];
var panelcount=0;
while (p) {
var defOpen=(p.substr(0,1)=="+"); if (defOpen) p=p.substr(1);
if (p.substr(0,3)=="id:")
{ id=p.substr(3); }
else if (p.substr(0,4)=="edit") {
panelcount++;
defOpen=defOpen || (!params[0] && panelcount==1); // if only one panel to show, default to open
var toolname=this.editorLabel;
if (p.indexOf('|')!=-1) toolname=p.substr(0,p.indexOf('|'));
selectors+=this.html.editorchk.replace(/%toolname%/mg,toolname);
selectors=selectors.replace(/%showpanel%/mg,defOpen?"CHECKED":"");
panels+=this.html.editorpanel;
// editor panel setup...
panels=panels.replace(/%showpanel%/mg,defOpen?"block":"none");
panels=panels.replace(/%maxrows%/mg,config.options.txtTidIDEMaxEditRows);
panels=panels.replace(/%disabled%/mg,readOnly?"DISABLED":"");
panels=panels.replace(/%readonlychk%/mg,readOnly?"CHECKED":"");
panels=panels.replace(/%minoredits%/mg,config.options.chkForceMinorUpdate&&!readOnly?"":"DISABLED");
panels=panels.replace(/%minorchk%/mg,config.options.chkForceMinorUpdate?"CHECKED":"");
var tiddlers=store.getTiddlers("title"); var tiddlerlist="";
for (var t=0; t<tiddlers.length; t++)
tiddlerlist+='<option value="'+tiddlers[t].title+'">'+tiddlers[t].title+'</option>';
for (var t in config.shadowTiddlers)
if (!store.tiddlerExists(t)) tiddlerlist+="<option value='"+t+"'>"+t+" (shadow)</option>";
panels=panels.replace(/%tiddlerlist%/mg,tiddlerlist);
var tags = store.getTags(); var taglist="";
for (var t=0; t<tags.length; t++)
taglist+="<option value='"+tags[t][0]+"'>"+tags[t][0]+"</option>";
panels=panels.replace(/%taglist%/mg,taglist);
if (p.substr(0,5)=="edit:") {
title=p.substr(5);
if (here && title=="here") title=here.id.substr(7);
}
}
else {
panelcount++;
defOpen=defOpen || (!params[0] && panelcount==1); // if only one panel to show, default to open
var toolid=toolname=p;
if (p.indexOf('|')!=-1)
{ toolname=p.substr(0,p.indexOf('|')); toolid=p.substr(p.indexOf('|')+1); }
selectors+=this.html.toolschk.replace(/%toolid%/mg,toolid).replace(/%toolname%/mg,toolname);
selectors=selectors.replace(/%showpanel%/mg,defOpen?"CHECKED":"");
panels+=this.html.toolspanel.replace(/%toolid%/mg,toolid);
panels=panels.replace(/%showpanel%/mg,defOpen?"block":"none");
if (defOpen) openpanels.push(toolid);
}
p=params.shift(); // next param
}
var html=this.html.framework;
if (panelcount<2)
html=html.replace(/%version%/mg,'').replace(/%selector%/mg,''); // omit header/selectors if just one panel to display
else {
html=html.replace(/%version%/mg,
this.versionMsg.format([version.extensions.tidIDE.major,version.extensions.tidIDE.minor,version.extensions.tidIDE.revision]));
html=html.replace(/%selector%/mg,selectors+"<hr style='margin:0;padding:0'>");
}
html=html.replace(/%panels%/mg,panels);
html=html.replace(/%id%/mg,id);
var newIDE=createTiddlyElement(place,"span");
newIDE.innerHTML=html;
if (title.length) this.set(id,title); // pre-load tiddler editor values (if needed)
if (openpanels.length) for (i=0;i<openpanels.length;i++) { config.macros.tidIDE.loadPanel(id,openpanels[i]); }
// see [[TextAreaPlugin]] for extended ctrl-F/G (search/search again)and TAB handler definitions
if (window.addKeyDownHandlers!=undefined) {
var elems=newIDE.getElementsByTagName("textarea");
for (var i=0;i<elems.length;i++) window.addKeyDownHandlers(elems[i]);
}
var prev=document.getElementById(id+'_previewpanel');
if (config.macros.preview && prev) // add previewer to editor (if installed)
config.macros.preview.handler(prev,"preview",["text","15"]);
}
//}}}
// // CUSTOM PANEL FUNCTIONS
//{{{
config.macros.tidIDE.loadPanel=function(id,toolid) {
var place=document.getElementById(id+"_"+toolid+"_panel"); if (!place) return;
var t=store.getTiddlerText(toolid,"");
place.innerHTML="";
if (t) wikify(t,place); else place.innerHTML=this.toolsDef.format([id,toolid]);
}
//}}}
// // EDITOR PANEL FUNCTIONS
//{{{
config.macros.tidIDE.set=function(id,title) {
var place=document.getElementById(id+"_editorpanel"); if (!place) return;
var f=document.getElementById(id+"_editorform");
if (f.dirty && !confirm(config.commands.cancelTiddler.warning.format([f.current]))) return;
// reset to form defaults
f.dirty=false;
f.current="";
f.created.value=f.created.defaultValue;
f.modified.value=f.modified.defaultValue;
f.author.value=f.author.defaultValue;
f.content.value=f.content.defaultValue;
f.tags.value=f.tags.defaultValue;
f.size.value=f.size.defaultValue;
if (!title.length) return;
f.current=title;
// values for new/shadow tiddlers
var cdate=new Date();
var mdate=new Date();
var modifier=config.options.txtUserName;
var text=config.views.editor.defaultText.format([title]);
var tags="";
// adjust values for shadow tiddlers
if (store.isShadowTiddler(title))
{ modifier=config.views.wikified.shadowModifier; text=store.getTiddlerText(title) }
// get values for specified tiddler (if it exists)
var t=store.getTiddler(title);
if (t) { var cdate=t.created; var mdate=t.modified; var modifier=t.modifier; var text=t.text; var tags=t.getTags(); }
if (!t && !store.isShadowTiddler(title)) f.tiddlers.options[f.tiddlers.options.length]=new Option(title,title,false,true); // add item to list
f.tiddlers.value=title; // select current title (just in case it wasn't already selected)
f.created.value=cdate.formatString(this.datetimefmt);
f.modified.value=mdate.formatString(this.datetimefmt);
f.author.value=modifier;
f.content.value=text;
f.tags.value=tags;
f.minoredits.checked=config.options.chkForceMinorUpdate&&!readOnly;
f.size.value=f.content.value.length+" bytes";
}
config.macros.tidIDE.add=function(id) {
var place=document.getElementById(id+"_editorpanel"); if (!place) return;
var f=document.getElementById(id+"_editorform");
if (f.dirty && !confirm(config.commands.cancelTiddler.warning.format([f.current]))) return;
var title=prompt(this.titleMsg,config.macros.newTiddler.title);
while (title && store.tiddlerExists(title) && !confirm(config.messages.overwriteWarning.format([title])))
title=prompt(this.titleMsg,config.macros.newTiddler.title);
if (!title || !title.trim().length) return; // cancelled by user
f.dirty=false; // suppress unneeded confirmation message
this.set(id,title);
}
config.macros.tidIDE.remove=function(id) {
var place=document.getElementById(id+"_editorpanel"); if (!place) return;
var f=document.getElementById(id+"_editorform");
if (!f.current.length) return;
if (!store.tiddlerExists(f.current) && store.isShadowTiddler(f.current)) { alert(this.isShadowMsg.format([f.current])); return; }
if (config.options.chkConfirmDelete && !confirm(config.commands.deleteTiddler.warning.format([f.current]))) return;
if (store.tiddlerExists(f.current)) {
story.closeTiddler(f.current);
store.removeTiddler(f.current);
store.setDirty(true);
if(config.options.chkAutoSave) saveChanges();
}
f.tiddlers.options[f.tiddlers.selectedIndex]=null; // remove item from list
f.dirty=false; // suppress unneeded confirmation message
this.set(id,""); // clear form controls
}
config.macros.tidIDE.save=function(id,saveAs) {
var place=document.getElementById(id+"_editorpanel"); if (!place) return;
var f=document.getElementById(id+"_editorform");
var title=f.current;
if (!title || !title.trim().length || saveAs) { // get a new title
title=prompt(this.titleMsg,config.macros.newTiddler.title);
while (title && store.tiddlerExists(title) && !confirm(config.messages.overwriteWarning.format([title])))
title=prompt(this.titleMsg,config.macros.newTiddler.title);
if (!title || !title.trim().length) return; // cancelled by user
f.tiddlers.options[f.tiddlers.options.length]=new Option(title,title,false,true); // add item to list
f.current=title;
}
var author=config.options.txtUserName;
var mdate=new Date();
var content=f.content.value;
var tags=f.tags.value;
var tiddler=store.saveTiddler(title,title,content,author,mdate,tags);
if (f.minoredits.checked) {
var author=f.author.value;
var mdate=new Date(f.modified.value);
var cdate=new Date(f.created.value);
tiddler.assign(null,null,author,mdate,null,cdate);
}
store.setDirty(true);
if(config.options.chkAutoSave) saveChanges();
story.refreshTiddler(title,null,true);
f.dirty=false;
}
//}}}
// // HTML DEFINITIONS
//{{{
config.macros.tidIDE.html = { };
config.macros.tidIDE.html.framework = " \
<html> %version% <form style='display:inline;margin:0;padding:0;'>%selector%</form> %panels% </html> \
";
//}}}
//{{{
config.macros.tidIDE.html.editorchk = " \
<input type=checkbox name=editor \
style='display:inline;width:auto;margin:1px;' \
title='add/delete/modify tiddlers' %showpanel% \
onclick='document.getElementById(\"%id%_editorpanel\").style.display=this.checked?\"block\":\"none\";'>%toolname% \
";
config.macros.tidIDE.html.toolschk = " \
<input type=checkbox name=tools \
style='display:inline;width:auto;margin:1px;' \
title='' %showpanel% \
onclick='document.getElementById(\"%id%_%toolid%_panel\").style.display=this.checked?\"block\":\"none\"; \
if (this.checked) config.macros.tidIDE.loadPanel(\"%id%\",\"%toolid%\");'>%toolname% \
";
//}}}
//{{{
config.macros.tidIDE.html.toolspanel = " \
<div id='%id%_%toolid%_panel' style='display:%showpanel%;margin:0;margin-top:0.5em'> \
</div> \
";
//}}}
//{{{
config.macros.tidIDE.html.editorpanel = " \
<div id='%id%_editorpanel' style='display:%showpanel%;margin:0;margin-top:0.5em'> \
<form id='%id%_editorform' style='display:inline;margin:0;padding:0;'> \
<!-- tiddler editor list and buttons --> \
<select size=1 name=tiddlers style='display:inline;width:44%;' \
onchange='config.macros.tidIDE.set(\"%id%\",this.value); this.value=this.form.current;'> \
<option value=''>select a tiddler...</option> \
%tiddlerlist% \
</select><!-- \
--><input name=add type=button style='display:inline;width:8%' \
value='new' title='create a new tiddler' \
onclick='config.macros.tidIDE.add(\"%id%\")' %disabled%><!-- \
--><input name=remove type=button style='display:inline;width:8%' \
value='remove' title='delete this tiddler' \
onclick='config.macros.tidIDE.remove(\"%id%\")' %disabled%><!-- \
--><input name=save type=button style='display:inline;width:8%' \
value='save' title='save changes to this tiddler' \
onclick='config.macros.tidIDE.save(\"%id%\")' %disabled%><!-- \
--><input name=saveas type=button style='display:inline;width:8%' \
value='save as' title='save changes to a new tiddler' \
onclick='config.macros.tidIDE.save(\"%id%\",true)' %disabled%><!-- \
--><input name=view type=button style='display:inline;width:8%' \
value='open' title='open this tiddler for regular viewing' \
onclick='if (!this.form.current.length) return; story.displayTiddler(null,this.form.current)'><!-- \
--><input name=run type=button style='display:inline;width:8%' \
value='run' title='evaluate this tiddler as a javascript \"systemConfig\" plugin' \
onclick='if (!confirm(config.macros.tidIDE.evalMsg.format([this.form.current]))) return false; \
try { window.eval(this.form.content.value); displayMessage(config.macros.tidIDE.evalCompletedMsg); } \
catch(e) { displayMessage(config.messages.pluginError.format([err])); }'><!-- \
--><input name=previewbutton type=button style='display:inline;width:8%;' \
value='preview' title='show \"live\" preview display' \
onclick='if (!config.macros.preview) { alert(\"Please install PreviewPlugin\"); return false; } \
this.form.preview.checked=!this.form.preview.checked; \
document.getElementById(\"%id%_previewpanel\").style.display=this.form.preview.checked?\"block\":\"none\"; \
if (this.form.freeze) this.form.freeze.checked=!this.form.preview.checked; \
if (this.form.preview.checked) config.macros.preview.render(this.form.content.id,this.form.content.getAttribute(\"previewid\"));'><!-- \
hidden field for preview show/hide state: \
--><input name=preview type=checkbox style='display:none;'>\
<!-- tiddler content edit --> \
<div><textarea id='%id%_content' name='content' edit='text' cols=60 rows=%maxrows% \
style='width:100%;' \
onkeyup='var f=this.form; f.dirty=true; f.size.value=this.value.length+\" bytes\";'></textarea></div> \
<!-- tag edit and droplist --> \
<table width='100%' style='border:0;padding:0;margin:0'><tr style='border:0;padding:0;margin:0'> \
<td style='border:0;padding:0;margin:0'> \
<input type=text name=tags size=60 style='width:100%;' value='' \
onchange='this.form.dirty=true' %disabled%> \
</td><td width='1' style='border:0;padding:0;margin:0;'> \
<select size=1 name=taglist \
onchange='this.form.dirty=true; this.form.tags.value+=\" \"+this.value' %disabled%> \
<option value=''>select tags...</option> \
%taglist% \
</select> \
</td></tr></table> \
<!-- created/modified dates, author, current tiddler size --> \
<div style='float:right;'> \
created <input type=text name=created size=15 \
style='display:inline;;text-align:center;padding:0;' value='' \
onchange='this.form.dirty=true' %minoredits%> \
modified <input type=text name=modified size=15 \
style='display:inline;text-align:center;padding:0;' value='' \
onchange='this.form.dirty=true;' %minoredits%> \
by <input type=text name=author size=15 \
style='display:inline;padding:0;' value='' \
onfocus='this.select()' onchange='this.form.dirty=true' %minoredits%> \
<input type=text name=size size=10 \
style='display:inline;text-align:center;padding:0;' value='' \
onfocus='this.blur()' onkeydown='return false' DISABLED> \
</div> \
<!-- toggles: read-only, minor edit --> \
<span style='white-space:nowrap'> \
<input type=checkbox name=readonly \
style='display:inline;width:auto;margin:1px;' %readonlychk% \
title='do not allow tiddler changes to be saved' \
onclick='readOnly=config.options.chkHttpReadOnly=this.checked;saveOptionCookie(\"chkHttpReadOnly\"); \
var f=this.form; f.minoredits.disabled=f.tags.disabled=f.taglist.disabled=this.checked; \
f.add.disabled=f.remove.disabled=f.save.disabled=f.saveas.disabled=this.checked; \
f.created.disabled=f.modified.disabled=f.author.disabled=this.checked||!f.minoredits.checked;'>readonly \
<input type=checkbox name=minoredits \
style='display:inline;width:auto;margin:1px;' %disabled% %minorchk% \
title='check: save datestamps/author as entered, uncheck: auto-update modified/author' \
onclick='this.form.created.disabled=this.form.modified.disabled=this.form.author.disabled=!this.checked; \
config.options.chkForceMinorUpdate=this.checked;saveOptionCookie(\"chkForceMinorUpdate\");'>minor edits \
</span> \
<!-- tiddler preview display --> \
<div id='%id%_previewpanel' style='display:none;white-space:nowrap'></div> \
";
//}}}
|Name|TidIDEPluginInfo|
|Source|http://www.TiddlyTools.com/#TidIDEPlugin|
|Documentation|http://www.TiddlyTools.com/#TidIDEPluginInfo|
|Version|1.8.3|
|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|documentation|
|Requires||
|Overrides||
|Description|documentation for TidIDEPlugin|
~TidIDE (//prounounced "Tie Dyed"//) - ''Tid''dlyWiki ''I''ntegrated ''D''evelopment ''E''nvironment - lets you define a set of checkboxes to toggle a stack of 'tool panels' containing tools for TiddlyWiki authors to use when creating and debugging their TiddlyWiki documents. Each tool is defined by a separate tiddler, allowing you to define any convenient set of tools simply by adding/removing tiddler references from the {{{<<tidIDE...>>}}} macro call.
In addition to presenting checkboxes/tool panels that are defined in separate tiddlers, the {{{<<tidIDE>>}}} macro can invoke an optional built-in "editor panel" that presents an alternative tiddler editor to create, modify, and manage the tiddlers in your document... and, if you have also installed [[PreviewPlugin]], the editor can automatically display a ''//formatted preview//'' of the current tiddler content that is updated ''live, key-by-key'' while you edit the tiddler source.
!!!!!Usage
<<<
Syntax:
{{{
<<tidIDE id:xyz TiddlerName ...>>
<<tidIDE id:xyz [[checkbox text|TiddlerName]] ...>>
<<tidIDE id:xyz edit ... >>
<<tidIDE id:xyz edit:here ... >>
<<tidIDE id:xyz edit:TidderName ...>>
}}}
where:
* ''id'' - assign a unique ID to this instance of TidIDE. (default id=current tiddler title or "" if not in a tiddler)
* ''{{{TidderName}}}'' or ''{{{[[checkbox text|TiddlerName]]}}}'' will include the custom tool panel content defined in TiddlerName (and a corresponding labelled checkbox to toggle its display)
* ''edit'' includes tiddler editor/previewer.
**''edit:here'' automatically sets the editor to show the current tiddler contents (if in a tiddler)
**''edit:tiddlertitle'' automatically sets the editor to show the specified tiddler contents
* all parameters are optional. The default panel is "edit:here".
* panel parameters preceded by a "+" are displayed by default. If only one panel specified in the parameters, it is automatically displayed, even if the "+" is omitted.
<<<
!!!!!Example
<<<
{{{<<tidIDE id:example SystemInfo TiddlerTweaker +edit:GettingStarted>>}}}
{{smallform{<<tidIDE id:example SystemInfo TiddlerTweaker +edit:GettingStarted>>}}}
<<<
!!!!!Using the built-in TidIDE editor
<<<
The editor includes a droplist of all tiddlers in the document, sorted alpha-numerically by tiddler title. Shadow tiddlers that have not been customized are added to the end of this list and marked with "(shadow)". Next to the droplist are several buttons:
* ''new'' prompts for a new tiddler title and begins a new editing session
* ''remove'' deletes an existing tiddler (note: shadow tiddlers cannot be removed)
* ''save'' saves changes to the tiddler currently being edited
* ''save as'' saves changes using a new tiddler title
* ''open'' opens the tiddler in the normal ~TiddlyWiki display area
* ''run'' invokes the tiddler as if it was a plugin (i.e., containing javascript code)
* ''preview'' toggles display of the live, key-by-key preview (when [[PreviewPlugin]] is installed)
If a tiddlername was not specified in the macro, select a tiddler from the droplist (or press ''add'') to begin editing. Once a tiddler has been loaded into the editor, you can change it's content, enter or select tags.
!!!!!minor edits
Normally, when you save changes to a tiddler, the created/modified dates and tiddler author are automatically updated. However, it is sometimes useful to make small changes to a tiddler without automatically updating the date/author information. Select the ''minor edits'' checkbox to prevent those values from being //automatically// changed. In addition, this enables the date/author edit fields which allows you to //manually// 'back date' a tiddler or change the author to another name. When the tiddler is saved, the date/author values shown in the edit fields will be used.
!!!!!using the previewer
When [[PreviewPlugin]] is installed, you can use the TidIDE editor's ''preview'' button to toggle the preview display area that shows you what your tiddler changes will look like, //before// committing to those changes. Please refer to the documentation in [[PreviewPlugin]] for more information.
<<<
!!!!!Revisions
<<<
2008.04.24 [1.8.3] fixed 'run' button onclick handler
2007.12.21 [1.8.1] added txtTidIDEMaxEditRows option as custom override for standard core txtMaxEditRows setting
2007.09.27 [1.8.0] split preview functionality into separate stand-alone plugin (see [[PreviewPlugin]]). Moved {{{<<DOMViewer>>}}} macro definition to separate plugin (see [[DOMViewerPlugin]]). Replicated ''run'' button functionality in stand-along plugin (see [[RunTiddlerPlugin]]). Major re-write of documentation
2007.09.13 [1.7.1] removed errant trailing comma from config.macros.tidIDE object definition (fixes IE error)
2007.09.09 [1.7.0] split systemInfo into separate plugin (see [[SystemInfoPlugin]])
2007.09.06 [1.6.3] in handler(), when using tiddler title as default instance ID, replace spaces with underscores to ensure generated form control ID's don't have embedded spaces.
2007.09.03 [1.6.2] in loadPanel(), use store.getTiddlerText() to permit use of shadow tiddlers as custom panels
2006.12.09 [1.6.1] in handler(), allow non-existing tiddler title when processing "edit:title" param
so that new tiddler (or journal) can be created directly from newTiddler, newJournal, or tidIDE macro (without pressing "new" button). Also, set 'edit=text' attribute on text area field so that default content can be initialized from "text:xxx" parameter specified in newTiddler/newJournal macro.
2006.11.28 [1.6.0] added font and size params to set CSS for form controls in editor and system info panels
2006.09.28 [1.5.8] use separate form ID and definition for each panel (as well as checkbox 'selector' form), so that forms in custom panels don't conflict with each other.
2006.08.27 [1.5.7] in handler(), corrected initial display setting for custom 'toolspanel' when '+' prefix has been used for 'defOpen'
2006.08.15 [1.5.6] in handler(), supress header/selectors if only one panel to display. Also, init system_panel as needed.
2006.08.04 [1.5.5] in handler(), fix construction of tiddler list to permit use of apostrophes (') in tiddler names.
2006.05.22 [1.5.4] in setsys(), remove "(cookie)" prefix from selected item text when setting cookie name (was preventing saving of cookie values)
2006.05.17 [1.5.3] in setsys(), call saveOptionsCookie(). Also, set tiddler editor textarea height (%maxrows%) using config.options.txtMaxEditRows
2006.04.30 [1.5.2] documentation update
2006.04.30 [1.5.1] in save(), when performing "save as" behavior, set current tiddler title (f.current) to new title
2006.04.24 [1.5.0] added macro parameters to dynamically configure and assemble HTML for IDE panels. Supports multiple custom panels loaded from tiddlers and {{{[[label|tiddlername]]}}}
2006.04.24 [1.4.6] layout adjustments: move system panel above editor panel and move config setting controls to top of system panel
2006.04.23 [1.4.5] fix HTML so that click on "readonly" checkbox won't change "minor edits" option value.
2006.04.23 [1.4.4] in render(), strip carriage returns (\r) that are added by IE's textarea control. Fixes errors in wikify() of 'block-mode' syntax. Also, defer rendering HTML and DOM preview displays until those options are checked and still more code cleanup
2006.04.23 [1.4.3] init "minor edits" checkbox state from config.options.chkForceMinorEdits value
2006.04.23 [1.4.2] added "TidIDE v#.#.#: " title in front of subsystem checkboxes.
2006.04.23 [1.4.1] added 'readonly' checkbox and handling to editor.
2006.04.23 [1.4.0] implemented 'minor edits' logic, including use of TW AdvancedOptions setting. Replaced separate MDY date input fields with date/time text input fields (using formatted date input).
2006.04.22 [1.3.2] Layout changes: Added editor/system/tools "subsystem" checkboxes at top of panel. Added automatic read-only notice. Moved tools_panel to bottom. Added 'minor edits' checkbox (handler not yet implemented).
2006.04.22 [1.3.1] assorted code cleanup and optimizations
2006.04.22 [1.3.0] added "tools" section via custom-defined TidIDETools tiddler content
2006.04.22 [1.2.2] corrected 'wrap' and 'white-space' CSS for system viewer textarea control so that IE preserves newlines.
2006.04.22 [1.2.1] added checkbox indicators in options droplist. Allows easy preview of boolean state value for chk* options.
2006.04.22 [1.2.0] added options droplist to "system" display and supporting setsys() function to update internal config.options.* values
layout adjustments: consolidate some buttons, general tweaks for spacing, sizes, etc.
2006.04.21 [1.1.1] migrated remaining functionality from ToolkitPlugin (now obsolete).
2006.04.21 [1.1.0] added "system" display and supporting functions
2006.04.21 [1.0.1] added formatHTML() for better HTML display in preview
2006.04.20 [1.0.0] 4:20:00pm official release... renamed from ~TiddlerEditorPlugin to TidIDEPlugin. (pronounced "Tie Dyed"... dude!)
2006.04.20 [0.9.9] added "run" button to dynamically load systemConfig plugins (with warning/confirmation)
2006.04.20 [0.9.8] layout adjustments for narrow displays
2006.04.20 [0.9.7] added HTML viewer to preview display
2006.04.20 [0.9.6] added DOM viewer to preview display
2006.04.19 [0.9.5] improved save() handler so saving 'unnamed' edit does fallback to 'save as' prompt for tiddler name
2006.04.19 [0.9.4] added 'preview status' display field and refresh button. Currently shows preview rendering time and autofreeze notice, if any.
2006.04.19 [0.9.3] correct IE object error by explicitly using "window." scope when referencing addKeyDownHandlers() function definition
2006.04.18 [0.9.2] if TextAreaPlugin is installed, call addKeyDownHandlers() for extended ctrl-F/G and TAB keystrokes in textarea
2006.04.18 [0.9.1] "save as" now presents an "overwriteWarning" message box instead of always rejecting existing tiddler titles
2006.04.18 [0.9.0] added "save as". Use TW standard text for new tiddler title and default text
2006.04.18 [0.8.5] added "display:inline" to input elements to prevent unwanted line breaks between controls when macro is used in EditTemplate definitions
2006.04.18 [0.8.4] added cookie for 'auto-freeze' time limit. Also, added more documentation.
2006.04.17 [0.8.3] added timing wrapper around preview wikify(). Automatically freeze preview display if tiddler rendering exceeds time limit
2006.04.17 [0.8.2] more code cleanup for better 'dirty' flag handling
2006.04.17 [0.8.1] show/hide freeze checkbox when toggling preview display. Also, code cleanup for better 'multiple instance' definition
2006.04.17 [0.8.0] added "freeze" checkbox to toggle 'live update' of preview display. Also, layout/CSS adjustments for better appearance in IE
2006.04.16 [0.7.1] correct month number offset (was 0-11 instead of 1-12)
2006.04.16 [0.7.0] added support for 'dirty' flag, read-only mode and improved alert/confirm/prompt handling
2006.04.16 [0.6.0] created "add/remove" functions. Added handling to trigger autoSave() if option is set.
2006.04.15 [0.5.1] move 'save' logic to separate function, and added handling to create a 'real' tiddler when saving a shadow
2006.04.15 [0.5.0] Initial ALPHA release. Converted from inline script.
<<<
! Demonstração por construção
''Teorema: para qualquer número par n>2 existe um grafo formado por apenas n vértices de grau 3''
Prova: Construa um grafo G=(V,E) da seguinte maneira:
V={0,1,....,n-1}
E={ {i,i+1} para $0<i le n-1$} $uu$ { {n-1,0}} $uu$ { {i,i+n/2} para $0 le i le n/2-1$}
> Desenhe o grafo e verifique.
! Demonstração por contradição
''Teorema: $sqrt 2$ é irracional''
1 - Supor $sqrt 2$ racional, assim, posso escrever na forma $m/n$ fração irredutível com m e n inteiros.
2 - $sqrt 2 = m/n => n sqrt 2 = m => 2 n^2 = m^2$
3 - $m^2$ é par, assim, m também é par porque o quadrado de um número ímpar é sempre ímpar.
4 - $m=2k$ com k inteiro
5 - Substituindo m=2k
$2n^2 = (2 k)^2 = 4 k^2$
$n^2=2k^2$
6 - n é portanto par.
7 - $m/n$ não é irredutível, pois m e n são pares.
8 - $sqrt 2$ não pode ser racional.
! Demonstração por indução
''Demonstrar que P(n): $sum_(i=0)^n i^2 = (n (n+1) (2n+1))/6$ ''
a) demonstro P(0)
P(0): $sum_(i=0)^0 i^2 =0 ; (0 (0+1) (0+1) )/6 =0$
b) demonstro P(n), supondo P(n-1) verdade
P(n-1): $ sum_(i=0)^(n-1) i^2 = ( (n-1)(n)(2n-2+1) )/6$
Somar $n^2$ em ambos os lados
$ sum_(i=0)^n i^2 = ( 2 n ^3- 2 n^2 - n^2 -n + 6 n^2 )/6 = ( 2 n^3 + 3 n^2 + n )/ 6 = (n (2 n^2 +3n+1) )/6 = (n (2n+1)(n+1))/6$
!Termos usados
Teorema: afirmação matemática provada verdadeira, geralmente de interesse particular.
Lema: como o teorema, mas com significado de resultado intermediário.
Corolário: como o teorema, mas com significado de resultado decorrente de uma afirmação mais importante.
!Outro exemplo de indução
''Prove que 3 é um fator de $n^3-n+3, AA n in NN$ ''
i) Para n=0 (base da indução)
$ 0^3 -0 +3 =3$
ii) passo indutivo
assumir verdadeiro: $n^3-n+3=3k$
$ (n+1)^3 - (n+1)+3 = n^3+3n^2+2n+3 = n^3-n+3 +(n^2+n)3 = 3k+3l=3(k+l) $
<<tiddler NextTiddler with: [[Linguagens]]>>
/***
|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");
//}}}
/***
|Name:|ToggleTagPlugin|
|Description:|Makes a checkbox which toggles a tag in a tiddler|
|Version:|3.1.0 ($Rev: 4907 $)|
|Date:|$Date: 2008-05-13 03:15:46 +1000 (Tue, 13 May 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 tiddlerTitle = tiddler ? tiddler.title : '';
var tag = (params[0] && params[0] != '.') ? params[0] : "checked";
var title = (params[1] && params[1] != '.') ? params[1] : tiddlerTitle;
var defaultLabel = (title == tiddlerTitle ? 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 == tiddlerTitle ? 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;
});
}
}
});
//}}}
//{{{
//replaces toolbar buttons with icons.
//for each command that you want to use an icon, add a line like the following in a systemConfig tiddler, specifying the icon image location:
//config.commands.editTiddler.imgLoc= "jump.bmp";
//No need to edit the ViewTemplate! If an image location is specified, then the icon will be used for that command!
config.macros.toolbar.createCommand = function(place,commandName,tiddler,theClass)
{
if(typeof commandName != "string")
{
var c = null;
for(var t in config.commands)
if(config.commands[t] == commandName)
c = t;
commandName = c;
}
if((tiddler instanceof Tiddler) && (typeof commandName == "string"))
{
var title = tiddler.title;
var command = config.commands[commandName];
var ro = tiddler.isReadOnly();
var shadow = store.isShadowTiddler(title) && !store.tiddlerExists(title);
var text = ro && command.readOnlyText ? command.readOnlyText : command.text;
var tooltip = ro && command.readOnlyTooltip ? command.readOnlyTooltip : command.tooltip;
if((!ro || (ro && !command.hideReadOnly)) && !(shadow && command.hideShadow))
{
var btn = createTiddlyButton(null,text,tooltip,this.onClickCommand);
btn.setAttribute("commandName", commandName);
btn.setAttribute("tiddler", title);
if(theClass)
addClass(btn,theClass);
place.appendChild(btn);
if(command.imgLoc)
btn.innerHTML = "<img src='"+command.imgLoc+"'>";
}
}
}
setStylesheet(".toolbarImg {vertical-align: middle; cursor:pointer;}\n","commandIconStyles");
//}}}
<!--{{{-->
<!--{{{-->
<div class='toolbar' macro='toolbar [[ToolbarCommands::ViewToolbar]]'></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>
<div class='viewer'> <span macro='view text wikified'></span> <span macro='navigation "" "" plugin'></span></div>
<!--}}}-->
<!--}}}-->
version.extensions.smileyMacro = {major: 0, minor: 1, revision: 0, date: new Date(2005,7,20)};
//Author: Alan Hecht
config.macros.smiley = {}
config.macros.smiley.handler = function(place,macroName,params)
{
var palette = ["transparent","#000000","#1a1507","#352e18","#464646","#666666","#a3141e","#b06b63","#cc9900","#dd9030","#dddddd","#e89d00","#edc32a","#f3cb3c","#fdf201","#fdf526","#ff3149","#ffac00","#ffbf06","#ffc846","#ffcc66","#ffd758","#ffdd01","#ffea7b","#ffed55","#ffffff"];
var data = params;
var imageMap = null;
if(data[0] == ":-)" || data[0] == ":)")
imageMap = "aaaaabbbbbaaaaaaaabdtyyvtdbaaaaabnyxxxxxujbaaabmyyffyffuujbaadyyyeeyeetttdabppppddyddpmmlbbwoooooooowsrlbbwwpooooowwmrlbbwwboooowwwbllbbwwwboooowbrllbacwwwbbbbbrllcaablswwwwsrrlibaaablsssrrllibaaaaabcrrlllcbaaaaaaaabbbbbaaaaa";
else if(data[0] == ":-(" || data[0] == ":(")
imageMap = "aaaaabbbbbaaaaaaaabdtyyvtdbaaaaabnyxxxxxujbaaabmyyyyyyyuujbaadyyyeeyeetttdabppppddyddpmmlbbwoooooooowsrlbbwwpooooowwmrlbbwwoooooowwrllbbwwwwbbbbbsrllbacwwbwwwwsbllcaablswwwwsrrlibaaablsssrrllibaaaaabcrrlllcbaaaaaaaabbbbbaaaaa";
else if(data[0] == ";-)" || data[0] == ";)")
imageMap = "aaaaabbbbbaaaaaaaabdtyyvtdbaaaaabnyxxxxxujbaaabmyyxxxxxuujbaadyyyxxxeetttdabppphddyddpmmlbbwoooooooowsrlbbwwpooooowwmrlbbwwboooowwwbllbbwwwboooowbrllbacwwwbbbbbrllcaablswwwwsrrlibaaablsssrrllibaaaaabcrrlllcbaaaaaaaabbbbbaaaaa";
else if(data[0] == ":-|" || data[0] == ":|")
imageMap = "aaaaabbbbbaaaaaaaabdtyyvtdbaaaaabnyxxxxxujbaaabmyyffyffuujbaadyyyeeyeetttdabppppddyddpmmlbbwoooooooowsrlbbwwpooooowwmrlbbwwoooooowwrllbbwwwwbbbbbsrllbacwwwwwwwsrllcaablswwwwsrrlibaaablsssrrllibaaaaabcrrlllcbaaaaaaaabbbbbaaaaa";
else if(data[0] == ":-D" || data[0] == ":D")
imageMap = "aaaaabbbbbaaaaaaaabdtyyvtdbaaaaabnyxxxxxujbaaabmyyeeyeeuujbaadyyyeeyeetttdabppppyyyyypmmlbbwbbbbbbbbbbblbbwbkzzzzzzzkbwbbwbfzzzzzzzfbwbbwbkzzzzzzzkbwbacwbkzzzzzkblcaablsbkzzzkblibaaablsbbbbblibaaaaabcrrlllcbaaaaaaaabbbbbaaaaa";
else
createTiddlyElement(place,"span",null,"errorNoSuchMacro","unknown smiley");
if(imageMap)
{
var box = createTiddlyElement(place,"span",null,"smiley",String.fromCharCode(160));
box.style.position = "relative";
box.style.width = "15px";
box.style.height = "15px";
box.style.marginLeft = "1px";
box.style.marginRight = "1px";
box.style.paddingRight = "12px";
box.style.verticalAlign = "top";
//now divide into 15x15 grid and create each pixel
// rows
for(r=0; r<15; r++)
{
// columns
for(c=0; c<15; c++)
{
//create each pixel with the correct background
var pix = document.createElement("img");
pix.className = "smileyPixel";
pix.style.position = "absolute";
pix.border = 0;
pix.style.top = r + "px";
pix.style.left = c + "px";
pix.style.width = "1px";
pix.style.height = "1px";
pix.style.backgroundColor = palette[imageMap.charCodeAt((r*15)+c)-97];
pix.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";
box.appendChild(pix);
}
}
}
}