How to use lookahead method in Playwright Internal

Best JavaScript code snippet using playwright-internal

t2tformatterplugin.tiddly

Source:t2tformatterplugin.tiddly Github

copy

Full Screen

1/***2|''Name:''|T2tFormatterPlugin|3|''Description:''|Allows Tiddlers to use [[txt2tags|http://txt2tags.org/markup.html]] formatting|4|''Author:''|David Young (david (dot) a (dot) young (at) gmail (dot) com)|5|''Credit:''|Copied and modified from Martin Budden's http://www.martinswiki.com/#ExampleFormatterPlugin |6|''CodeRepository:''|NA |7|''Version:''|0.4|8|''Status:''|Rough Draft|9|''Date:''|Jul 5, 2011|10|''Comments:''|Please make comments at http://groups.google.co.uk/group/TiddlyWikiDev |11|''License:''|NA |12|''~CoreVersion:''|2.6.1|13! Installation Instructions14Apply the following tags to this tiddler:15* systemConfig16* excludeLists17* excludeSearch18You can make a tiddler with the tag ''t2t'' and the Txt2Tags markup will be used instead of TiddlyWiki markup. You can eliminate the need to manually tag by modifying your ''Create New Tiddler'' macro in your [[MainMenu]] to set the //wikiformat// field to ''t2t'':19{{{20<<newTiddler21label: "New t2t"22title: "New t2t tiddler"23fields: "wikiformat:t2t"24prompt: "Create a new tiddler using the t2t formatter">>25}}}26You should also get into [[AdvancedOptions]] or //backstage -> Tweaks -> chkInsertTabs// because that lets you hit the tab button in the tiddly text field. Tab will still move your cursor around the page, from title input to tiddly text input, etc. It only effects the text field. Vital for t2t blockquote syntax (prepending with tabs).27!Features/ Progress28| ''Markup'' | ''Feature'' | ''Status'' | ''Version'' | ''Comment'' |29| several | \n vs. \r in input | ''WAITING'' | NA |Applied to tagged and raw, but I am uncertain if this is OK.<br>Emailed twdev mailing list. |30| ''FONT/INLINE'' |||||31|{{{**}}}''bold''{{{**}}} | All | ''OK'' | 0.1 |Hasn't been heavily tested on any platform. |32|{{{//}}}//italic//{{{//}}} | All | ''OK'' | 0.1 |Hasn't been heavily tested on any platform. |33|{{{__}}}__under__{{{__}}} | All | ''OK'' | 0.1 |Hasn't been heavily tested on any platform. |34|{{{--}}}--strike--{{{--}}} | All | ''OK'' | 0.1 |Hasn't been heavily tested on any platform.|35|{{{^^}}}^^super^^{{{^^}}} | All | ''OK'' | 0.1 |Hasn't been heavily tested on any platform.<br>Not Official Markup.|36|{{{,,}}}~~sub~~{{{,,}}} | All | ''OK'' | 0.1 |Hasn't been heavily tested on any platform.<br>Not Official Markup.|37|{{{``monospace``}}} | All | ''OK'' | 0.1 |Hasn't been heavily tested on any platform.|38|{{{''}}}tagged/html{{{''}}} | All | ''OK'' | 0.1 |Hasn't been heavily tested on any platform.|39|{{{""}}}raw{{{""}}} | All | ''OK'' | 0.1 |Hasn't been heavily tested on any platform.<br>Overrides WikiWords and Markup.|40| ''SINGLE-LINE'' |||||41|{{{``` monospace}}} | All | ''OK'' | 0.1 |Hasn't been heavily tested on any platform. |42|{{{'''}}} tagged/html | All | ''OK'' | 0.1 |Hasn't been heavily tested on any platform. |43|{{{"""}}} raw | All | ''OK'' | 0.1 |Hasn't been heavily tested on any platform. |44|{{{%}}}comments | ALL | ''OK'' | 0.1 |Hasn't been heavily tested on any platform. |45| ''BLOCKS'' |||||46|{{{```}}}<br>{{{monospace}}}<br>{{{```}}} | All | ''OK'' | 0.1 |Hasn't been heavily tested on any platform. |47|{{{'''}}}<br>tagged/html<br>{{{'''}}} | All | ''OK'' | 0.1 |Hasn't been heavily tested on any platform. |48|{{{"""}}}<br>raw<br>{{{"""}}} | All | ''OK'' | 0.1 |Hasn't been heavily tested on any platform. |49|{{{%%%}}}<br>comments<br>{{{%%%}}} | All | ''OK'' | 0.1 |Hasn't been heavily tested on any platform |50|\t<html>&nbsp;&nbsp;&nbsp;&nbsp;</html>block<br>\t<html>&nbsp;&nbsp;&nbsp;&nbsp;</html>quotes | All | ''OK'' | 0.1 |Hasn't been heavily tested on any platform.<br>Tiddlywiki interprets all markup inside the block; unlike txt2tags (only some markup). |51| ''HEADERS'' |||||52|{{{=}}}un-numbered{{{=}}} | ALL | ''OK'' | 0.1 |Hasn't been heavily tested on any platform. |53|{{{+}}}numbered{{{+}}} | HEADING | ''OK'' | 0.1 |Hasn't been heavily tested on any platform. |54|{{{+}}}numbered{{{+}}} | NUMBERING | ''OK'' | 0.1 |Hasn't been heavily tested on any platform.<br>Unknown if array length modification or array[6] reassignment is faster on a per-iteration basis. |55| ''MISC'' |||||56|horizontal rule<br>{{{--------------------}}} | RULE | ''OK'' | 0.1 |Hasn't been heavily tested on any platform. |57|{{{====================}}}<br>{{{____________________}}}| THICKNESS | ''??'' | 0.1 |The alternative rules are interpreted and classes //heavy// or //light// are assigned; but my theme doesn't use them so I can't tell.<br>Maybe tiddlywiki doesn't use those css classes at all?<br>If so, delete this functionality. |58|Paragraphs | ALL | ''CAN'T FIX'' | 0.1 |Multiple newlines are concatenated into {{{<p><\p>}}}.<br>Visually they appear correctly (line spacing, etc), but it isn't a real paragraph.<br>If you try to make {{{<p>}}} elements wrap the text, then they are nested improperly if you look at the html.<br>This nesting lead to a stack busting on tiddlers if you have around 200 paragraphs or more.<br>This resulted in content truncation, so {{{<p><\p>}}} it shall be.<br>Historical bug in tiddlywiki's core, so I can't do much about it.<br>This is certainly a kludge, maybe {{{<br><br>}}} would be better, but that seems equally kludgy and all block-type syntax must be careful. |59| ''LISTS'' |||||60|{{{- }}}unordered | ALL | ''OK'' | 0.1 |t2t allows complex lists (paragraphs inside list items).<br>Can't figure out a good regex to match "X blank lines" that works with paragraph.<br>Interim solution: terminate list with empty item. |61|{{{+ }}}ordered | ALL | ''OK'' | 0.1 |t2t allows complex lists (paragraphs inside list items).<br>Can't figure out a good regex to match "X blank lines" that works with paragraph.<br>Interim solution: terminate list with empty item.<br>INTERFERES WITH NUMBERED HEADINGS. |62|{{{: }}}word<br><html>&nbsp;&nbsp;&nbsp;&nbsp;</html>definitions | ALL | ''TIDDLY'' | NA |Difficult to pull off since "definition" part of t2t uses whitespaces.<br>Interim solution: use tiddlywiki ; word \n : definition format. |63| ''COMPLEX'' |||||64|~WikiWords | ALL | ''TIDDLY'' | 0.1 |Self-updating link to core formatter.<br>Not Official Markup. |65|{{{<<macros>>}}} | ALL | ''TIDDLY'' | 0.1 |Self-updating link to core formatter.<br>By changing the header syntax, the {{{<<tiddler##section>>}}} section transclusion macro won't work.<br>Not Official Markup. |66|http url recognition | ALL | ''TIDDLY'' | 0.1 |Self-updating link to core formatter.<br>Not Official Markup. |67|email recognition | ALL | ''NA'' | NA |Is this at all worth it? t2t will mask or convert to mailto...<br>don't take this lightly- it wrecked the works last time. |68|{{{[}}}links{{{]}}} | ALL | ''OK'' | 0.1 |Links to internal tiddlers (as long as their title has no spaces), links to external websites |69|{{{[}}}named links{{{]}}} | ALL | ''OK'' | 0.1 |Links to internal tiddlers (as long as their title has no spaces), links to external websites |70|'image-related' | ALL | ''OK'' | 0.1 |an image or image link supports whitespace-alignment.<br>If the {{{[}}} starts at the newline, the image will float to the left (equivalent to the {{{<}}} markup in tiddly images).<br>If the {{{]}}} ends the line, the image will float to the right (equivalent to the {{{>}}} markup in tiddly images).<br>If the image is both the start and end of line, it is neither left nor right.<br>No centering image support yet. |71|{{{[}}}images{{{]}}} | ALL | ''OK'' | 0.1 |Supports .png .gif .jpg .jpeg, just grep for IMAGE-EXTENSION-REGEX in this tiddler to expand the list.<br>Works for local and external image files |72|{{{[[image] links]}}} | ALL | ''OK'' | 0.1 |A twist here is that the link can have spaces in the name, but I don't recommend trying that. |73|{{{|}}}tables{{{|}}} | ALL | ''TIDDLY'' | 0.1 |Tiddlywiki tables are supported. Self-updating link to core formatter. |74***/75//{{{76//REGEXES found in txt2tags.py:1920 (getRegexes)77// Ensure that the plugin is only installed once.78if(!version.extensions.T2tFormatterPlugin) {79version.extensions.T2tFormatterPlugin = {installed:true};80//Should test this backwards until I find the revision that is actually useless81if(version.major < 2 || (version.major == 2 && version.minor < 6))82 {alertAndThrow('T2tFormatterPlugin requires TiddlyWiki 2.6 or later.');}83t2tFormatter = {}; // 'namespace' for local functions84t2tDebug = function(out,str)85{86 createTiddlyText(out,str.replace(/\n/mg,'\\n').replace(/\r/mg,'RR'));87 createTiddlyElement(out,'br');88};89/*90wikify = function(source,output,highlightRegExp,tiddler)91{92 if(source && source !== '') {93 var w = new Wikifier(source,getParser(tiddler),highlightRegExp,tiddler);94 w.output = tiddler ? createTiddlyElement(output,'p') : output;95 w.subWikifyUnterm(w.output);96 }97};98*/99// COPY from EnclosedTextHelper Tiddlywiki v2.6.1 line 2923100// If the lookaheadRegexp fails, use the string in "restore:"101// define the element "restore:" as the static string equal to your102// "match:"'s result.103//104// If your markup rules are more complex/less dynamic (like ==headers==);105// then you must copy this and make up your own combo of parenthesis.106config.formatterHelpers.nonDestructiveEnclosedTextHelper = function(w)107{108 this.lookaheadRegExp.lastIndex = w.matchStart;109 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);110 if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {111 //Everything that uses this function is a one-liner syntax112 /*113 var text = lookaheadMatch[1];114 if(config.browser.isIE)115 text = text.replace(/\n/g,"\r");116 createTiddlyElement(w.output,this.element,null,null,text);117 */118 //createTiddlyElement(w.output,this.element,null,null,lookaheadMatch[1]);119 w.subWikifyTerm(createTiddlyElement(w.output,this.element),this.termRegExp);120 w.nextMatch = lookaheadMatch.index + lookaheadMatch[0].length;121 } else {122 w.output.appendChild(document.createTextNode(w.matchText));123 }124};125/*126// Like nonDestructiveEnclosedTextHelper, only you can define what is127// restored with a regular expression instead of a static string.128// This is helpful for when the "match" is more dynamic. Just define129// element "restoreRegExp:" and the first parenthesis in it will be used130// to restore the consumed "match" text.131// NOTE: this comes at the cost of ANOTHER grepping of your input!132config.formatterHelpers.nonDestructiveEnclosedTextHelperRegEx = function(w)133{134 this.lookaheadRegExp.lastIndex = w.matchStart;135 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);136 if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {137 var text = lookaheadMatch[1];138 if(config.browser.isIE)139 text = text.replace(/\n/g,"\r");140 createTiddlyElement(w.output,this.element,null,null,text);141 w.nextMatch = lookaheadMatch.index + lookaheadMatch[0].length;142 } else {143 this.restoreRegExp.lastIndex = w.matchStart;144 var restoreMatch = this.restoreRegExp.exec(w.source);145 if (restoreMatch && restoreMatch.index == w.matchStart) {146 w.output.appendChild(document.createTextNode(restoreMatch[1]));147 } else {148 //shouldn't be possible!149 //Only if you don't define restoreRegExp: properly150 w.output.appendChild(document.createTextNode("### SYNTAX ERROR ###"));151 }152 }153};154*/155/*156config.formatterHelpers.setAttributesFromParams = function(e,p)157{158 var re = /\s*(.*?)=(?:(?:"(.*?)")|(?:'(.*?)')|((?:\w|%|#)*))/mg;159 var match = re.exec(p);160 while(match) {161 var s = match[1].unDash();162 if(s=='bgcolor') {163 s = 'backgroundColor';164 }165 try {166 if(match[2]) {167 e.setAttribute(s,match[2]);168 } else if(match[3]) {169 e.setAttribute(s,match[3]);170 } else {171 e.setAttribute(s,match[4]);172 }173 }174 catch(ex) {}175 match = re.exec(p);176 }177};178*/179config.t2tFormatters = [180//SPEED: COMBINE ALL BEAUTIFIERS LIKE TIDDLY DOES ALREADY181// bold uses syntax **bold** no whitespace in the bookends.182{183 name: 't2tBold',184 match: '\\*\\*',185 element: 'strong',186 lookaheadRegExp: /\*\*([^\s](|.*?[^\s])\**)\*\*/mg,187 termRegExp: /(\*\*)/mg,188 handler: config.formatterHelpers.nonDestructiveEnclosedTextHelper189},190// italic uses //italic//191{192 name: 't2tItalic',193 match: '//',194 element: 'em',195 lookaheadRegExp: /\/\/([^\s](|.*?[^\s])[\/]*)(\/\/)/mg,196 termRegExp: /(\/\/)/mg,197 handler: config.formatterHelpers.nonDestructiveEnclosedTextHelper198},199// Horizontal rules can be made up of 20 or more - characters on a line with200// whitespace on the ends. Alternatively 20 or more _ characters is accepted.201// 20 or more = characters also work, but that makes a "thicker" horizontal rule202// see t2tHeavyRule.203{204 name: 't2tRule',205 match: '^[ \\t]*[-_]{20,}[ \\t]*$',206 handler: function(w)207 {208 createTiddlyElement(w.output,'hr',null,'light');209 }210},211// Default tiddler theme doesn't differentiate between heavy and light.212// TODO: Try some other themes otherwise roll this into t2tRule.213{214 name: 't2tHeavyRule',215 match: '^[ \\t]*={20,}[ \\t]*$',216 handler: function(w)217 {218 createTiddlyElement(w.output,'hr',null,'heavy');219 }220},221// underline uses __underline__222{223 name: 't2tUnderline',224 match: '__',225 element: 'ins',226 lookaheadRegExp: /__([^\s](|.*?[^\s])_*)__/mg,227 termRegExp: /(__)/mg,228 handler: config.formatterHelpers.nonDestructiveEnclosedTextHelper229},230// strikethrough uses --strike--231{232 name: 't2tStrike',233 match: '--',234 element: 'del',235 lookaheadRegExp: /--([^\s](|.*?[^\s])-*)--/mg,236 termRegExp: /(--)/mg,237 handler: config.formatterHelpers.nonDestructiveEnclosedTextHelper238},239/*240// superscript uses ^^super^^241// this is unofficial242{243 name: 't2tSuperscript',244 match: '\\^\\^',245 element: 'sup',246 lookaheadRegExp: /\^\^([^\s](|.*?[^\s])\^*)\^\^/mg,247 handler: config.formatterHelpers.nonDestructiveEnclosedTextHelper248},249// subscript uses ,,sub,,250// this is unofficial251{252 name: 't2tSubscript',253 match: ',,',254 element: 'sub',255 lookaheadRegExp: /,,([^\s](|.*?[^\s]),*),,/mg,256 handler: config.formatterHelpers.nonDestructiveEnclosedTextHelper257},258*/259// Monospace uses different variants of backticks260// blocks are bordered with lines containing only 3 backticks261// ```262{263 name: 't2tMonospaceBlock',264 match: '^```[ \\t]*$',265 lookaheadRegExp: /^```[ \t]*(?:\n?((?:.|\n)*?\n)```[ \t]*$)|((?:.|\n)*$)/gm,266 handler: function(w) {267 this.lookaheadRegExp.lastIndex = w.matchStart;268 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);269 if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {270 if (lookaheadMatch[1]) {271 var text = lookaheadMatch[1];272 } else {273 var text = lookaheadMatch[2].substr(w.matchLength+1);274 }275 if(config.browser.isIE)276 text = text.replace(/\n/g,"\r");277 createTiddlyElement(w.output,"pre",null,null,text);278 w.nextMatch = this.lookaheadRegExp.lastIndex;279 } else w.output.appendChild(document.createTextNode(w.matchText));280 }281},282// lines prefixed with 3 backticks are preformatted blocks as well283// one block per line! putting backtic-prefixed lines consecutively will284// result in 2 preformatted blocks!285//SPEED: this can be like tiddly's termregexp syntax like a "Heading"286{287 name: 't2tMonospaceLine',288 match: '^``` ',289 lookaheadRegExp: /^``` ((?:.)*?)$/mg,290 element: 'pre',291 handler: config.formatterHelpers.enclosedTextHelper292},293// inline monospaced text ``like this``.294// terminates at the first newline without matching backtics.295// this version uses code instead of pre.296{297 name: 't2tMonospace',298 match: '``',299 element: 'code',300 lookaheadRegExp: /``([^\s](|.*?[^\s])`*)``/mg,301 termRegExp: /(``)/mg,302 handler: config.formatterHelpers.nonDestructiveEnclosedTextHelper303},304//t2tCommentblock305{306 name: 't2tCommentBlock',307 match: '^%%%[ \\t]*\\n',308 //emptyblock but no unclosed trailer309 //lookaheadRegExp: /^%%%[ \t]*((?:.|\n)*?)\n%%%[ \t]*(\n|$)/mg,310 // match next %%% line OR match to EOF311 lookaheadRegExp: /^%%%[ \t]*(?:(?:[.|\n]*?)\n%%%[ \t]*$)|(?:[.\n]*$)/gm,312 handler: function(w)313 {314 this.lookaheadRegExp.lastIndex = w.matchStart;315 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);316 if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {317 w.nextMatch = this.lookaheadRegExp.lastIndex;318 } else w.output.appendChild(document.createTextNode(w.matchText));319 }320},321//SPEED: this can be like tiddly's termregexp syntax like a "Heading"322{323 name: 't2tCommentLine',324 match: '^%' ,325 lookaheadRegExp: /^%.*?$/mg,326 handler: function(w)327 {328 this.lookaheadRegExp.lastIndex = w.matchStart;329 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);330 if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {331 w.nextMatch = this.lookaheadRegExp.lastIndex;332 } else w.output.appendChild(document.createTextNode(w.matchText));333 }334},335// nonstandard br insertion336// I like tex's \\337{338 name: 't2tLineBreak',339 match: '\\\\\\\\',340 handler: function(w)341 {342 createTiddlyElement(w.output,'br');343 }344},345//TODO: tagged text doesn't get the \n \r IE replacement... test in IE346// t2t tagged text is "passthrough" so what you type is passed on to347// the html interpreter. t2t formatting isn't converted into html.348// Raw html is interpreted by your browser.349// Tagged uses various forms of single-quotes.350// multi-line blocks are bordered by lines containing only '''351{352 name: 't2tTaggedBlock',353 match: '^\'\'\'[ \\t]*$',354 lookaheadRegExp: /^'''[ \t]*(?:((?:.|\n)*?\n)'''[ \t]*$)|((?:.|\n)*$)/gm,355 handler: function(w)356 {357 this.lookaheadRegExp.lastIndex = w.matchStart;358 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);359 if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {360 if (lookaheadMatch[1]) {361 var text = lookaheadMatch[1];362 } else {363 var text = lookaheadMatch[2].substr(w.matchLength+1);364 }365 if(config.browser.isIE)366 text = text.replace(/\n/g,"\r");367 createTiddlyElement(w.output,"span").innerHTML = text;368 w.nextMatch = this.lookaheadRegExp.lastIndex;369 } else w.output.appendChild(document.createTextNode(w.matchText));370 }371},372// Single lines prepended with ''' will be considered "tagged"373// Unlike monospace, tagged isn't really a "block" so having multiple374// pre-pended lines won't look any different than one multi-line block.375//SPEED: this can be like tiddly's termregexp syntax like a "Heading"376{377 name: 't2tTaggedLine',378 match: '^\'\'\' ',379 lookaheadRegExp: /^''' ((?:.)*?)$/mg,380 handler: function(w)381 {382 this.lookaheadRegExp.lastIndex = w.matchStart;383 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);384 if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {385 createTiddlyElement(w.output,"span").innerHTML = lookaheadMatch[1];386 w.nextMatch = this.lookaheadRegExp.lastIndex;387 } else w.output.appendChild(document.createTextNode(w.matchText));388 }389},390// inline tagged text is wrapped ''in 2 single quotes''. This type ends at391// the newline if there is no matching ''.392{393 name: 't2tTagged',394 match: '\'\'',395 lookaheadRegExp: /''([^\s](|.*?[^\s])'*)''/mg,396 handler: function(w)397 {398 this.lookaheadRegExp.lastIndex = w.matchStart;399 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);400 if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {401 createTiddlyElement(w.output,"span").innerHTML = lookaheadMatch[1];402 w.nextMatch = this.lookaheadRegExp.lastIndex;403 } else w.output.appendChild(document.createTextNode(w.matchText));404 }405},406//TODO: RAW text doesn't get the \n \r IE replacement... test in IE407// t2t Raw text ignores t2t formatting (any wiki formatting); but characters408// are still 'escaped' out to be displayed by the brower.409// e.g. ""**bold**"" isn't made bold; you see the astrices; while lines using410// html tags will convert angle brackets to < >411// This is synonymous with nowiki412// Blocks of raw text are bordered with blank lines of 3 double quotes.413{414 name: 't2tRawBlock',415 match: '^\\"\\"\\"[ \\t]*$',416 lookaheadRegExp: /^"""[ \t]*(?:((?:.|\n)*?\n)"""[ \t]*$)|((?:.|\n)*$)/gm,417 handler: function(w)418 {419 this.lookaheadRegExp.lastIndex = w.matchStart;420 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);421 if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {422 if (lookaheadMatch[1]) {423 var text = lookaheadMatch[1];424 } else {425 var text = lookaheadMatch[2].substr(w.matchLength+1);426 }427 //rawblock may not work with this properly?428 if(config.browser.isIE)429 text = text.replace(/\n/g,"\r");430 createTiddlyElement(w.output,"span",null,null,text);431 w.nextMatch = this.lookaheadRegExp.lastIndex;432 } else w.output.appendChild(document.createTextNode(w.matchText));433 }434},435// Any line prepended with 3 double quotes is interpreted as raw.436// Unlike monospace, raw isn't really a "block" so consecutive pre-pended lines437// will have no difference with a multi-line block.438//SPEED: this can be like tiddly's termregexp syntax like a "Heading"439{440 name: 't2tRawLine',441 match: '^\\"\\"\\" ',442 lookaheadRegExp: /^""" ((?:.)*?)$/mg,443 handler: function(w)444 {445 this.lookaheadRegExp.lastIndex = w.matchStart;446 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);447 if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {448 createTiddlyElement(w.output,'span',null,null,lookaheadMatch[1]);449 w.nextMatch = this.lookaheadRegExp.lastIndex;450 } else w.output.appendChild(document.createTextNode(w.matchText));451 }452},453// The in-line format uses 2 double quotes ""raw"".454// The end of the line terminates raw if there is no matching "".455{456 name: 't2tRaw',457 match: '\\"\\"',458 lookaheadRegExp: /""([^\s](|.*?[^\s])"*)""/mg,459 handler: function(w)460 {461 this.lookaheadRegExp.lastIndex = w.matchStart;462 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);463 if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {464 createTiddlyElement(w.output,'span',null,null,lookaheadMatch[1]);465 w.nextMatch = this.lookaheadRegExp.lastIndex;466 } else w.output.appendChild(document.createTextNode(w.matchText));467 }468},469// Section headings are bookended by matching sets of = signs.470// It must all be on one line471//SPEED: simplify match472{473 name: 't2tHeading',474 //no whitespace at the start475 //match: '^ *={1,6}[^=\n]',476 //lookaheadRegExp: /^ *(={1,6})([^=\n][^\n]*[^=\n])\1[ \t]*$/mg,477 match: '^={1,6}[^ =\n]',478 lookaheadRegExp: /^(={1,6})([^ =\n][^\n]*[^=\n])\1[ \t]*$/mg,479 handler: function(w)480 {481 this.lookaheadRegExp.lastIndex = w.matchStart;482 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);483 if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {484 //headings in t2t don't allow markup inside, so we DO NOT use the subwikifyterm here.485 createTiddlyElement(w.output,'h'+lookaheadMatch[1].length,null,null,lookaheadMatch[2]);486 w.nextMatch = lookaheadMatch.index + lookaheadMatch[0].length;487 } else w.output.appendChild(document.createTextNode(w.matchText));488 }489},490/*491//This breaks everything. T2T converts emails into mailto:s or it masks them:492// dave@gmail.com --> <dave (AT) gmail dOT com>493{494 name: 't2tEmailHiding',495 match: '[\\w]+(\\.[\\w\\-\\+_]+)*\\@[\\w\\-\\+_]+\\.[\\w\\-\\+_]+(\\.[\\w\\-\\+_]+)*',496 lookaheadRegExp: /([\w]+(?:\.[\w\-\+_]+)*)\@([\w\-\+_]+\.[\w\-\+_]+(?:\.[\w\-\+_]+)*)/mg,497 handler: function(w)498 {499 this.lookaheadRegExp.lastIndex = w.matchStart;500 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);501 if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {502 var text = '<' + lookaheadMatch[1] + " (AT) " + lookaheadMatch[2] + '>';503 text = text.replace(/\./g," DOT ");504 createTiddlyElement(w.output,"span",null,null,text);505 w.nextMatch = this.lookaheadRegExp.lastIndex;506 }507 }508},509*/510// push-pop version keeps the array sized to whatever it should be. This is511// probably faster than the array reassignment (below this function) especially512// in the simplest and more likely use case: only using top-level headings.513// In practice, though, 10k numbered headings takes forever in BOTH cases.514// HTML doesn't have an inherent number scheme for header tags. Just treat515// them as unnumbered for now.516// SPEED: simplify match. see what termregexp can do.517{518 name: 't2tNumberedHeading',519 //no whitespace at the start.520 //match: '^ *\\+{1,6}[^\\+\\n]',521 //lookaheadRegExp: /^ *(\+{1,6})([^\+\n][^\n]*[^\+\n])\1[ \t]*$/mg,522 match: '^\\+{1,6}[^ \\+\\n]',523 lookaheadRegExp: /^(\+{1,6})([^ \+\n][^\n]*[^\+\n])\1[ \t]*$/mg,524 handler: function(w)525 {526 if (! w.numheading) {527 w.numheading = [0,0];528 }529 this.lookaheadRegExp.lastIndex = w.matchStart;530 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);531 if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {532 var text = lookaheadMatch[2];533 // since length=1 == arrayindex 0534 var headingindex = lookaheadMatch[1].length - 1;535 // since length1 means we want 2 items in the array536 var targetlength = headingindex + 2;537 //add or remove values until numheading.length = lookaheadMatch[1].length538 //push 0's first to add539 for (var i = w.numheading.length; i < targetlength; i++) 540 w.numheading.push(0);541 //removing is eashy, you can just change length and it truncates array (garbage later)542 w.numheading.length = targetlength;543 //increment this heading544 w.numheading[headingindex]++;545 //reset the next level down to 0546 w.numheading[headingindex + 1] = 0;547 text = " " + text;548 for (headingindex; headingindex >= 0; headingindex--) {549 text = w.numheading[headingindex] + "." + text;550 }551 createTiddlyElement(w.output,'h'+lookaheadMatch[1].length,null,null,text);552 w.nextMatch = lookaheadMatch.index + lookaheadMatch[0].length;553 } else w.output.appendChild(document.createTextNode(w.matchText));554 }555},556// t2t concatenates newlines to make paragraphs.557// WARNING: tiddly doesn't support this very well; the appearance is558// OK but the dynamic HTML has oddly-nested paragraphs.559{560 name: 't2tParagraph',561 match: '\\n{2,}',562 handler: function(w)563 {564 //do you like stack overflows in your html engine?565 //try making 200 paragraphs with this.566 //createTiddlyElement(w.output,'p');567 //Looks ok-ish, but now you have manual BR's mixed in568 //with the implied whitespace by an <h1> or <quote>.569 //createTiddlyElement(w.output,'br');570 //createTiddlyElement(w.output,'br');571 //ohh this is so wrong to do, but it works pretty well.572 //no stack explosions, and it looks visually correct.573 createTiddlyElement(w.output,"span").innerHTML = "<p></p>";574 }575},576{577 name: 't2tLinkImg',578 match: '(?:^\\[)|(?:\\[)',579 // ([^\n\r]*?) matches 2 separate entities: [foo] and [soft]580 // ([^\n\r]*) matches entity: [(foo] and [soft)]581 // use *? or include [] us unallowed chaaracters582 lookaheadRegExp: /(?:(^\[)|(?:\[))(?:(\[([^\[\]\n\r\f]+)\] ?([^\n\r\[\]]*))|([^\s\[\]]+)|(([^\[\]\n\r\f]+) ([^\[\]\s]+)))(?:(\]$)|(?:\]))/mg,583 handler: function(w)584 {585 this.lookaheadRegExp.lastIndex = w.matchStart;586 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);587 if(lookaheadMatch && lookaheadMatch.index == w.matchStart)588 {589 //first and last group match for alignment to be used for images.590 if (lookaheadMatch[1] && (! lookaheadMatch[9]))591 {592 var imagealign = "left";593 }594 else if ( (! lookaheadMatch[1]) && lookaheadMatch[9])595 {596 var imagealign = "right";597 }598 //alignment discovered, now see what type of bracket link.599 // [[image] link]600 //2 = imglink; 3 img 4 link601 if (lookaheadMatch[2])602 {603 var e = w.output;604 // 4 may not exist, it could just be an image formatted [[image]]605 if (lookaheadMatch[4]) {606 var link = lookaheadMatch[4];607 e = config.formatterHelpers.isExternalLink(link) ?608 createExternalLink(w.output,link) :609 createTiddlyLink(w.output,link,false,null,w.isStatic,w.tiddler);610 addClass(e,"imageLink");611 }612 var img = createTiddlyElement(e,"img");613 if (imagealign) img.align = imagealign;614 img.src = lookaheadMatch[3];615 img.title = lookaheadMatch[4];616 img.setAttribute("alt",lookaheadMatch[4]);617 w.nextMatch = this.lookaheadRegExp.lastIndex;618 /*619 if (align)620 {621 alert( align+"-ed image\nfile: '"+lookaheadMatch[3]+"'\nurl: '"+lookaheadMatch[4]+"'");622 } else {623 alert( "unaligned image\nfile: '"+lookaheadMatch[3]+"'\nurl: '"+lookaheadMatch[4]+"'");624 }625 */626 }627 // [link] or [image] 628 //5 = url or img629 else if (lookaheadMatch[5])630 {631 // IMAGE-EXTENSION-REGEX632 if (/\.((gif)|(je?pg)|(png)|(bmp)|(tif))$/i.exec(lookaheadMatch[5]))633 {634 //alert("image extension found");635 var e = w.output;636 var img = createTiddlyElement(e,"img");637 if (imagealign) img.align = imagealign;638 img.src = lookaheadMatch[5];639 img.title = lookaheadMatch[5];640 img.setAttribute("alt",lookaheadMatch[5]);641 w.nextMatch = this.lookaheadRegExp.lastIndex;642 /*643 if (align)644 {645 alert( align+"-ed image\nfile: '"+lookaheadMatch[5]+"'");646 } else {647 alert( "unaligned image\nfile: '"+lookaheadMatch[5]+"'");648 }649 */650 }651 else652 {653 //alert("no image extension found");654 //obviously this isn't an image by the extension, so it is just a link.655 var link = lookaheadMatch[5];656 var e = (config.formatterHelpers.isExternalLink(link)) ?657 createExternalLink(w.output,link) :658 createTiddlyLink(w.output,link,false,null,w.isStatic,w.tiddler);659 createTiddlyText(e,link);660 w.nextMatch = this.lookaheadRegExp.lastIndex;661 //alert("Simple link to url: '"+lookaheadMatch[5]+"'");662 }663 }664 // [some name text linkWithNoSpaces] the existence of a space is the key!665 //6 named link 7 = name 8 = link666 else if (lookaheadMatch[6])667 {668 var text = lookaheadMatch[7];669 var link = lookaheadMatch[8];670 var e = (config.formatterHelpers.isExternalLink(link)) ?671 createExternalLink(w.output,link) :672 createTiddlyLink(w.output,link,false,null,w.isStatic,w.tiddler);673 createTiddlyText(e,text);674 w.nextMatch = this.lookaheadRegExp.lastIndex;675 //alert( "name: '"+lookaheadMatch[8]+"'\nurl: '"+lookaheadMatch[9]+"'");676 } else w.output.appendChild(document.createTextNode(w.matchText));677 } else w.output.appendChild(document.createTextNode(w.matchText));678 }679},680// COPY from tiddlywiki code681{682 name: "t2tList",683 match: "^(?:[ ]*[\\+-;:] )",684 //lookaheadRegExp: /^(?:[ ]*(?:(-)|(\+)|(:)|( )) )/mg,685 lookaheadRegExp: /^(?:[ ]*(?:(-)|(\+)|(;)|(:)) )/mg,686 //http://stackoverflow.com/questions/5531899/regex-do-not-include-a-substring-within-a-group/5531972#5531972687 // V~do include this if it matched688 termRegExp: /(\n(?:(?=[ ]*[\+;:-] )|[ ]*[\+;:-]))/mg,689 // ^~lookahead for this but don't include it690 handler: function(w)691 {692 //if (! w.lengths) {693 w.lengths = [0];694 //}695 var stack = [w.output];696 var currLevel = 0, currType = null;697 var listLevel, listType, itemType, baseType;698 w.nextMatch = w.matchStart;699 this.lookaheadRegExp.lastIndex = w.nextMatch;700 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);701 while(lookaheadMatch && lookaheadMatch.index == w.nextMatch) {702 if(lookaheadMatch[1]) {703 listType = "ul";704 itemType = "li";705 } else if(lookaheadMatch[2]) {706 listType = "ol";707 itemType = "li";708 } else if(lookaheadMatch[3]) {709 listType = "dl";710 itemType = "dt";711 } else if(lookaheadMatch[4]) {712 listType = "dl";713 itemType = "dd";714 }715 if(!baseType)716 baseType = listType;717 //fill levelstack718 var l = lookaheadMatch[0].length719 while ( w.lengths[w.lengths.length-1] != l ) {720 if ( l > w.lengths[w.lengths.length-1] ) {721 w.lengths.push(l);722 break;723 } else {724 w.lengths.pop();725 }726 }727 listLevel = w.lengths.length-1;728 w.nextMatch += l;729 var t;730 if(listLevel > currLevel) {731 for(t=currLevel; t<listLevel; t++) {732 var target = (currLevel == 0) ? stack[stack.length-1] : stack[stack.length-1].lastChild;733 stack.push(createTiddlyElement(target,listType));734 }735 } else if(listType!=baseType && listLevel==1) {736 w.nextMatch -= lookaheadMatch[0].length;737 return;738 } else if(listLevel < currLevel) {739 for(t=currLevel; t>listLevel; t--)740 stack.pop();741 } else if(listLevel == currLevel && listType != currType) {742 stack.pop();743 stack.push(createTiddlyElement(stack[stack.length-1].lastChild,listType));744 }745 currLevel = listLevel;746 currType = listType;747 var e = createTiddlyElement(stack[stack.length-1],itemType);748 w.subWikifyTerm(e,this.termRegExp);749 this.lookaheadRegExp.lastIndex = w.nextMatch;750 lookaheadMatch = this.lookaheadRegExp.exec(w.source);751 }752 }753},754/*755//array reassignment version. I think that the up-to-6 assignments per iteration756//could have worse performance that resizing the array.757//see above for array re-sizing.758// HTML doesn't have an inherent number scheme for header tags. Just treat759// them as unnumbered for now.760{761 name: 't2tNumberedHeading',762 match: '^ *\\+{1,6}[^\\+\n]',763 lookaheadRegExp: / *(\+{1,6})([^\+\n][^\n]*[^\+\n])\1[ \t]*$/mg,764 handler: function(w)765 {766 if (! w.numheading) {767 w.numheading = [0,0,0,0,0,0];768 }769 this.lookaheadRegExp.lastIndex = w.matchStart;770 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);771 if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {772 var text = lookaheadMatch[2];773 var headingindex = lookaheadMatch[1].length - 1;774 w.numheading[headingindex]++;775 //reset the next levels down to 0776 for(var i = headingindex + 1; i<=5; i++){777 w.numheading[i] = 0;778 }779 text = " " + text;780 for (headingindex; headingindex >= 0; headingindex--) {781 text = w.numheading[headingindex] + "." + text;782 }783 createTiddlyElement(w.output,'h'+lookaheadMatch[1].length,null,null,text);784 w.nextMatch = lookaheadMatch.index + lookaheadMatch[0].length;785 } else {786 w.output.appendChild(document.createTextNode(w.matchText));787 }788 }789},790*/791// t2t prepends TABs on lines that form blockquotes.792// Consecutive lines of the same depth of tabs are in the same block.793// This is just like tiddly markup, only they use angle brackets.794// Thus, I am ripping this code from a 2.6.1 formatters.795{796 name: 't2tQuoteByLine',797 match: '\\t+',798 lookaheadRegExp: /^\t+/mg,799 termRegExp: /(\n)/mg,800 element: 'blockquote',801 handler: function(w)802 {803 var stack = [w.output];804 var currLevel = 0;805 var newLevel = w.matchLength;806 var t;807 do {808 if(newLevel > currLevel) {809 for(t=currLevel; t<newLevel; t++)810 stack.push(createTiddlyElement(stack[stack.length-1],this.element));811 } else if(newLevel < currLevel) {812 for(t=currLevel; t>newLevel; t--)813 stack.pop();814 }815 currLevel = newLevel;816 w.subWikifyTerm(stack[stack.length-1],this.termRegExp);817 //originally they insert linebreaks... not in t2t818 //createTiddlyElement(stack[stack.length-1],'br');819 //replace the newline that was consumed820 if(config.browser.isIE) {821 var e = document.createTextNode('\r');822 } else {823 var e = document.createTextNode('\n');824 }825 stack[stack.length-1].appendChild(e);826 this.lookaheadRegExp.lastIndex = w.nextMatch;827 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);828 var matched = lookaheadMatch && lookaheadMatch.index == w.nextMatch;829 if(matched) {830 newLevel = lookaheadMatch[0].length;831 w.nextMatch += lookaheadMatch[0].length;832 }833 } while(matched);834 }835},836/*837//COPY from tiddlywiki config.formatters838{839 name: "macro",840 match: "<<",841 ////don't start new macro << HERE 842 //lookaheadRegExp: /<<([^>\s(?:<<)]+)(?:\s*)((?:[^>]|(?:>(?!>)))*)>>/mg,843 lookaheadRegExp: /<<([^>\s]+)(?:\s*)((?:[^>]|(?:>(?!>)))*)>>/mg,844 handler: function(w)845 {846 this.lookaheadRegExp.lastIndex = w.matchStart;847 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);848 if(lookaheadMatch && lookaheadMatch.index == w.matchStart && lookaheadMatch[1]) {849 w.nextMatch = this.lookaheadRegExp.lastIndex;850 invokeMacro(w.output,lookaheadMatch[1],lookaheadMatch[2],w,w.tiddler);851 //with this modification for nondestructiveness.852 } else {853 w.output.appendChild(document.createTextNode(w.matchText));854 }855 }856},857*/858];859t2tReuse = function(name)860{861 var i;862 for (i = 0; i < config.formatters.length; i++) {863 if (name == config.formatters[i].name)864 return config.formatters[i];865 }866 return null;867 868};869//attach reused formatters from standard config.formatters.870config.t2tFormatters.push(t2tReuse("macro"));871config.t2tFormatters.push(t2tReuse("wikiLink"));872config.t2tFormatters.push(t2tReuse("urlLink"));873config.t2tFormatters.push(t2tReuse("htmlEntitiesEncoding"));874//config.t2tFormatters.push(t2tReuse("mdash"));875config.t2tFormatters.push(t2tReuse("table"));876/*877var text = "t2tFormatters:\n";878for (var i=0; i < config.t2tFormatters.length; i++)879 text = text + config.t2tFormatters[i].name + "\n";880alert(text);881*/882config.parsers.t2tFormatter = new Formatter(config.t2tFormatters);883config.parsers.t2tFormatter.format = 't2t';884config.parsers.t2tFormatter.formatTag = 't2t';885} // end of 'install only once'886//}}}887/***888vim: ft=javascript...

Full Screen

Full Screen

wikitextrules.js

Source:wikitextrules.js Github

copy

Full Screen

1/*\2title: $:/plugins/tiddlywiki/tw2parser/wikitextrules.js3type: application/javascript4module-type: module5Rule modules for the wikitext parser6\*/7(function(){8/*jslint node: true, browser: true */9/*global $tw: false */10"use strict";11var macroadapter = require("$:/macros/classic/macroadapter.js");12var textPrimitives = {13 upperLetter: "[A-Z\u00c0-\u00de\u0150\u0170]",14 lowerLetter: "[a-z0-9_\\-\u00df-\u00ff\u0151\u0171]",15 anyLetter: "[A-Za-z0-9_\\-\u00c0-\u00de\u00df-\u00ff\u0150\u0170\u0151\u0171]",16 anyLetterStrict: "[A-Za-z0-9\u00c0-\u00de\u00df-\u00ff\u0150\u0170\u0151\u0171]",17 sliceSeparator: "::",18 sectionSeparator: "##",19 urlPattern: "(?:file|http|https|mailto|ftp|irc|news|data):[^\\s'\"]+(?:/|\\b)",20 unWikiLink: "~",21 brackettedLink: "\\[\\[([^\\]]+)\\]\\]",22 titledBrackettedLink: "\\[\\[([^\\[\\]\\|]+)\\|([^\\[\\]\\|]+)\\]\\]"23};24textPrimitives.wikiLink = "(?:(?:" + textPrimitives.upperLetter + "+" +25 textPrimitives.lowerLetter + "+" +26 textPrimitives.upperLetter +27 textPrimitives.anyLetter + "*)|(?:" +28 textPrimitives.upperLetter + "{2,}" +29 textPrimitives.lowerLetter + "+))";30textPrimitives.cssLookahead = "(?:(" + textPrimitives.anyLetter +31 "+)\\(([^\\)\\|\\n]+)(?:\\):))|(?:(" + textPrimitives.anyLetter + "+):([^;\\|\\n]+);)";32textPrimitives.cssLookaheadRegExp = new RegExp(textPrimitives.cssLookahead,"mg");33textPrimitives.tiddlerForcedLinkRegExp = new RegExp("(?:" + textPrimitives.titledBrackettedLink + ")|(?:" +34 textPrimitives.brackettedLink + ")|(?:" +35 textPrimitives.urlPattern + ")","mg");36textPrimitives.tiddlerAnyLinkRegExp = new RegExp("("+ textPrimitives.wikiLink + ")|(?:" +37 textPrimitives.titledBrackettedLink + ")|(?:" +38 textPrimitives.brackettedLink + ")|(?:" +39 textPrimitives.urlPattern + ")","mg");40// Helper to add an attribute to an HTML node41var setAttr = function(node,attr,value) {42 if(!node.attributes) {43 node.attributes = {};44 }45 node.attributes[attr] ={type: "string", value:value} ;46};47var inlineCssHelper = function(w) {48 var styles = [];49 textPrimitives.cssLookaheadRegExp.lastIndex = w.nextMatch;50 var lookaheadMatch = textPrimitives.cssLookaheadRegExp.exec(w.source);51 while(lookaheadMatch && lookaheadMatch.index == w.nextMatch) {52 var s,v;53 if(lookaheadMatch[1]) {54 s = lookaheadMatch[1];55 v = lookaheadMatch[2];56 } else {57 s = lookaheadMatch[3];58 v = lookaheadMatch[4];59 }60 if(s=="bgcolor")61 s = "backgroundColor";62 if(s=="float")63 s = "cssFloat";64 styles.push({style: s, value: v});65 w.nextMatch = lookaheadMatch.index + lookaheadMatch[0].length;66 textPrimitives.cssLookaheadRegExp.lastIndex = w.nextMatch;67 lookaheadMatch = textPrimitives.cssLookaheadRegExp.exec(w.source);68 }69 return styles;70};71var applyCssHelper = function(e,styles) {72 if(styles.length > 0) {73 for(var t=0; t< styles.length; t++) {74 $tw.utils.addStyleToParseTreeNode(e,$tw.utils.roundTripPropertyName(styles[t].style),styles[t].value);75 }76 }77 78};79var enclosedTextHelper = function(w) {80 this.lookaheadRegExp.lastIndex = w.matchStart;81 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);82 if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {83 var text = lookaheadMatch[1];84 w.output.push({type:"element",tag:this.element,85 children:[{type: "text",text: lookaheadMatch[1]}]});86 w.nextMatch = lookaheadMatch.index + lookaheadMatch[0].length;87 }88};89var insertMacroCall = function(w,output,macroName,paramString) {90 var params = [],91 reParam = /\s*(?:([A-Za-z0-9\-_]+)\s*:)?(?:\s*(?:"""([\s\S]*?)"""|"([^"]*)"|'([^']*)'|\[\[([^\]]*)\]\]|([^"'\s]+)))/mg,92 paramMatch = reParam.exec(paramString);93 while(paramMatch) {94 // Process this parameter95 var paramInfo = {96 value: paramMatch[2] || paramMatch[3] || paramMatch[4] || paramMatch[5] || paramMatch[6]97 };98 if(paramMatch[1]) {99 paramInfo.name = paramMatch[1];100 }101 params.push(paramInfo);102 // Find the next match103 paramMatch = reParam.exec(paramString);104 }105 output.push({106 type: "macrocall",107 name: macroName,108 params: params,109 isBlock: false110 });111}112var isLinkExternal = function(to) {113 var externalRegExp = /(?:file|http|https|mailto|ftp|irc|news|data|skype):[^\s'"]+(?:\/|\b)/i;114 return externalRegExp.test(to);115};116var rules = [117{118 name: "table",119 match: "^\\|(?:[^\\n]*)\\|(?:[fhck]?)$",120 lookaheadRegExp: /^\|([^\n]*)\|([fhck]?)$/mg,121 rowTermRegExp: /(\|(?:[fhck]?)$\n?)/mg,122 cellRegExp: /(?:\|([^\n\|]*)\|)|(\|[fhck]?$\n?)/mg,123 cellTermRegExp: /((?:\x20*)\|)/mg,124 rowTypes: {"c":"caption", "h":"thead", "":"tbody", "f":"tfoot"},125 handler: function(w)126 {127 var table = {type:"element",tag:"table",attributes: {"class": {type: "string", value:"table"}},128 children: []};129 130 w.output.push(table);131 var prevColumns = [];132 var currRowType = null;133 var rowContainer;134 var rowCount = 0;135 w.nextMatch = w.matchStart;136 this.lookaheadRegExp.lastIndex = w.nextMatch;137 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);138 while(lookaheadMatch && lookaheadMatch.index == w.nextMatch) {139 var nextRowType = lookaheadMatch[2];140 if(nextRowType == "k") {141 table.attributes["class"] = lookaheadMatch[1];142 w.nextMatch += lookaheadMatch[0].length+1;143 } else {144 if(nextRowType != currRowType) {145 rowContainer = {type:"element",tag:this.rowTypes[nextRowType],children: []};146 table.children.push(rowContainer);147 currRowType = nextRowType;148 }149 if(currRowType == "c") {150 // Caption151 w.nextMatch++;152 // Move the caption to the first row if it isn't already153 if(table.children.length !== 1) {154 table.children.pop(); // Take rowContainer out of the children array155 table.children.splice(0,0,rowContainer); // Insert it at the bottom 156 }157 rowContainer.attributes={};158 rowContainer.attributes.align = rowCount === 0 ? "top" : "bottom";159 w.subWikifyTerm(rowContainer.children,this.rowTermRegExp);160 } else {161 var theRow = {type:"element",tag:"tr",162 attributes: {"class": {type: "string", value:rowCount%2 ? "oddRow" : "evenRow"}},163 children: []};164 165 rowContainer.children.push(theRow);166 this.rowHandler(w,theRow.children,prevColumns);167 rowCount++;168 }169 }170 this.lookaheadRegExp.lastIndex = w.nextMatch;171 lookaheadMatch = this.lookaheadRegExp.exec(w.source);172 }173 },174 rowHandler: function(w,e,prevColumns)175 {176 var col = 0;177 var colSpanCount = 1;178 var prevCell = null;179 this.cellRegExp.lastIndex = w.nextMatch;180 var cellMatch = this.cellRegExp.exec(w.source);181 while(cellMatch && cellMatch.index == w.nextMatch) {182 if(cellMatch[1] == "~") {183 // Rowspan184 var last = prevColumns[col];185 if(last) {186 last.rowSpanCount++;187 $tw.utils.addAttributeToParseTreeNode(last.element,"rowspan",last.rowSpanCount);188 var vAlign = $tw.utils.getAttributeValueFromParseTreeNode(last.element,"valign","center");189 $tw.utils.addAttributeToParseTreeNode(last.element,"valign",vAlign);190 if(colSpanCount > 1) {191 $tw.utils.addAttributeToParseTreeNode(last.element,"colspan",colSpanCount);192 colSpanCount = 1;193 }194 }195 w.nextMatch = this.cellRegExp.lastIndex-1;196 } else if(cellMatch[1] == ">") {197 // Colspan198 colSpanCount++;199 w.nextMatch = this.cellRegExp.lastIndex-1;200 } else if(cellMatch[2]) {201 // End of row202 if(prevCell && colSpanCount > 1) {203 prevCell.attributes.colspan = colSpanCount;204 }205 w.nextMatch = this.cellRegExp.lastIndex;206 break;207 } else {208 // Cell209 w.nextMatch++;210 var styles = inlineCssHelper(w);211 var spaceLeft = false;212 var chr = w.source.substr(w.nextMatch,1);213 while(chr == " ") {214 spaceLeft = true;215 w.nextMatch++;216 chr = w.source.substr(w.nextMatch,1);217 }218 var cell;219 if(chr == "!") {220 cell = {type:"element",tag:"th",children: []};221 e.push(cell);222 w.nextMatch++;223 } else {224 cell = {type:"element",tag:"td",children: []};225 e.push(cell);226 }227 prevCell = cell;228 prevColumns[col] = {rowSpanCount:1,element:cell};229 if(colSpanCount > 1) {230 $tw.utils.addAttributeToParseTreeNode(cell,"colspan",colSpanCount);231 colSpanCount = 1;232 }233 applyCssHelper(cell,styles);234 w.subWikifyTerm(cell.children,this.cellTermRegExp);235 if (!cell.attributes) cell.attributes ={};236 if(w.matchText.substr(w.matchText.length-2,1) == " ") // spaceRight237 $tw.utils.addAttributeToParseTreeNode(cell,"align",spaceLeft ? "center" : "left");238 else if(spaceLeft)239 $tw.utils.addAttributeToParseTreeNode(cell,"align","right");240 w.nextMatch--;241 }242 col++;243 this.cellRegExp.lastIndex = w.nextMatch;244 cellMatch = this.cellRegExp.exec(w.source);245 }246 }247},248{249 name: "heading",250 match: "^!{1,6}",251 termRegExp: /(\n)/mg,252 handler: function(w)253 {254 var e = {type:"element",tag:"h" + w.matchLength,children: []};255 w.output.push(e);256 w.subWikifyTerm(e.children,this.termRegExp);257 }258},259{260 name: "list",261 match: "^(?:[\\*#;:]+)",262 lookaheadRegExp: /^(?:(?:(\*)|(#)|(;)|(:))+)/mg,263 termRegExp: /(\n)/mg,264 handler: function(w)265 {266 var stack = [w.output];267 var currLevel = 0, currType = null;268 var listLevel, listType, itemType, baseType;269 w.nextMatch = w.matchStart;270 this.lookaheadRegExp.lastIndex = w.nextMatch;271 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);272 while(lookaheadMatch && lookaheadMatch.index == w.nextMatch) {273 if(lookaheadMatch[1]) {274 listType = "ul";275 itemType = "li";276 } else if(lookaheadMatch[2]) {277 listType = "ol";278 itemType = "li";279 } else if(lookaheadMatch[3]) {280 listType = "dl";281 itemType = "dt";282 } else if(lookaheadMatch[4]) {283 listType = "dl";284 itemType = "dd";285 }286 if(!baseType)287 baseType = listType;288 listLevel = lookaheadMatch[0].length;289 w.nextMatch += lookaheadMatch[0].length;290 var t,e;291 if(listLevel > currLevel) {292 for(t=currLevel; t<listLevel; t++) {293 var target = stack[stack.length-1];294 if(currLevel !== 0 && target.children) {295 target = target.children[target.children.length-1];296 }297 e = {type:"element",tag:listType,children: []};298 target.push(e);299 stack.push(e.children);300 }301 } else if(listType!=baseType && listLevel==1) {302 w.nextMatch -= lookaheadMatch[0].length;303 return;304 } else if(listLevel < currLevel) {305 for(t=currLevel; t>listLevel; t--)306 stack.pop();307 } else if(listLevel == currLevel && listType != currType) {308 stack.pop();309 e = {type:"element",tag:listType,children: []};310 stack[stack.length-1].push(e);311 stack.push(e.children);312 }313 currLevel = listLevel;314 currType = listType;315 e = {type:"element",tag:itemType,children: []};316 stack[stack.length-1].push(e);317 w.subWikifyTerm(e.children,this.termRegExp);318 this.lookaheadRegExp.lastIndex = w.nextMatch;319 lookaheadMatch = this.lookaheadRegExp.exec(w.source);320 }321 }322},323{324 name: "quoteByBlock",325 match: "^<<<\\n",326 termRegExp: /(^<<<(\n|$))/mg,327 element: "blockquote",328 handler: function(w) {329 var e = {type:"element",tag:this.element,children: []};330 w.output.push(e);331 w.subWikifyTerm(e.children,this.termRegExp);332 }333},334{335 name: "quoteByLine",336 match: "^>+",337 lookaheadRegExp: /^>+/mg,338 termRegExp: /(\n)/mg,339 element: "blockquote",340 handler: function(w)341 {342 var stack = [];343 var currLevel = 0;344 var newLevel = w.matchLength;345 var t,matched,e;346 do {347 if(newLevel > currLevel) {348 for(t=currLevel; t<newLevel; t++) {349 var f = stack[stack.length-1];350 e = {type:"element",tag:this.element,children: []};351 stack.push(e);352 if (t ===0){353 w.output.push(e);354 }else {355 f.children.push(e);356 357 }358 }359 } else if(newLevel < currLevel) {360 for(t=currLevel; t>newLevel; t--)361 stack.pop();362 }363 currLevel = newLevel;364 w.subWikifyTerm(stack[stack.length-1].children,this.termRegExp);365 stack[stack.length-1].children.push({type:"element",tag:"br"});366 //e.push({type:"element",tag:"br"});367 this.lookaheadRegExp.lastIndex = w.nextMatch;368 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);369 matched = lookaheadMatch && lookaheadMatch.index == w.nextMatch;370 if(matched) {371 newLevel = lookaheadMatch[0].length;372 w.nextMatch += lookaheadMatch[0].length;373 }374 } while(matched);375 }376},377{378 name: "rule",379 match: "^----+$\\n?|<hr ?/?>\\n?",380 handler: function(w)381 {382 w.output.push({type:"element",tag:"hr"});383 }384},385{386 name: "monospacedByLine",387 match: "^(?:/\\*\\{\\{\\{\\*/|\\{\\{\\{|//\\{\\{\\{|<!--\\{\\{\\{-->)\\n",388 element: "pre",389 handler: function(w)390 {391 switch(w.matchText) {392 case "/*{{{*/\n": // CSS393 this.lookaheadRegExp = /\/\*\{\{\{\*\/\n*((?:^[^\n]*\n)+?)(\n*^\f*\/\*\}\}\}\*\/$\n?)/mg;394 break;395 case "{{{\n": // monospaced block396 this.lookaheadRegExp = /^\{\{\{\n((?:^[^\n]*\n)+?)(^\f*\}\}\}$\n?)/mg;397 break;398 case "//{{{\n": // plugin399 this.lookaheadRegExp = /^\/\/\{\{\{\n\n*((?:^[^\n]*\n)+?)(\n*^\f*\/\/\}\}\}$\n?)/mg;400 break;401 case "<!--{{{-->\n": //template402 this.lookaheadRegExp = /<!--\{\{\{-->\n*((?:^[^\n]*\n)+?)(\n*^\f*<!--\}\}\}-->$\n?)/mg;403 break;404 default:405 break;406 }407 enclosedTextHelper.call(this,w);408 }409},410{411 name: "typedBlock",412 match: "^\\$\\$\\$(?:[^ >\\r\\n]*)\\r?\\n",413 lookaheadRegExp: /^\$\$\$([^ >\r\n]*)\n((?:^[^\n]*\r?\n)+?)(^\f*\$\$\$\r?\n?)/mg,414 //match: "^\\$\\$\\$(?:[^ >\\r\\n]*)(?: *> *([^ \\r\\n]+))?\\r?\\n",415 //lookaheadRegExp: /^\$\$\$([^ >\r\n]*)(?: *> *([^ \r\n]+))\n((?:^[^\n]*\n)+?)(^\f*\$\$\$$\n?)/mg,416 handler: function(w)417 {418 this.lookaheadRegExp.lastIndex = w.matchStart;419 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);420 if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {421 // The wikitext parsing infrastructure is horribly unre-entrant422 var parseType = lookaheadMatch[1],423 renderType ,//= this.match[2],424 text = lookaheadMatch[2],425 oldOutput = w.output,426 oldSource = w.source,427 oldNextMatch = w.nextMatch,428 oldChildren = w.children;429 // Parse the block according to the specified type430 var parser = $tw.wiki.parseText(parseType,text.toString(),{defaultType: "text/plain"});431 w.output = oldOutput;432 w.source = oldSource;433 w.nextMatch = oldNextMatch;434 w.children = oldChildren;435 for (var i=0; i<parser.tree.length; i++) {436 w.output.push(parser.tree[i]);437 }438 w.nextMatch = this.lookaheadRegExp.lastIndex;439 }440 }441},442{443 name: "wikifyComment",444 match: "^(?:/\\*\\*\\*|<!---)\\n",445 handler: function(w)446 {447 var termRegExp = (w.matchText == "/***\n") ? (/(^\*\*\*\/\n)/mg) : (/(^--->\n)/mg);448 w.subWikifyTerm(w.output,termRegExp);449 }450},451{452 name: "macro",453 match: "<<",454 lookaheadRegExp: /<<(?:([!@£\$%\^\&\*\(\)`\~'"\|\\\/;\:\.\,\+\=\-\_\{\}])|([^>\s]+))(?:\s*)((?:[^>]|(?:>(?!>)))*)>>/mg,455 handler: function(w)456 {457 this.lookaheadRegExp.lastIndex = w.matchStart;458 var lookaheadMatch = this.lookaheadRegExp.exec(w.source),459 name;460 if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {461 name = lookaheadMatch[1] || lookaheadMatch[2];462 var params = lookaheadMatch[3], nameold =name;463 if (name) {464 if (!!macroadapter.paramadapter[name]) {465 params=macroadapter.paramadapter[name](params);466 //alert("going out as "+params);467 }468 if (!!macroadapter.namedapter[name]) {469 name=macroadapter.namedapter[name];470 }471 w.nextMatch = this.lookaheadRegExp.lastIndex;472 insertMacroCall(w,w.output,name,params);473 }474 }475 }476},477{478 name: "prettyLink",479 match: "\\[\\[",480 lookaheadRegExp: /\[\[(.*?)(?:\|(~)?(.*?))?\]\]/mg,481 handler: function(w)482 {483 this.lookaheadRegExp.lastIndex = w.matchStart;484 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);485 if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {486 var text = lookaheadMatch[1],487 link = text;488 if(lookaheadMatch[3]) {489 // Pretty bracketted link490 link = lookaheadMatch[3];491 }492 if(isLinkExternal(link)) {493 w.output.push({494 type: "element",495 tag: "a",496 attributes: {497 href: {type: "string", value: link},498 "class": {type: "string", value: "tc-tiddlylink-external"},499 target: {type: "string", value: "_blank"}500 },501 children: [{502 type: "text", text: text503 }]504 });505 } else {506 w.output.push({507 type: "link",508 attributes: {509 to: {type: "string", value: link}510 },511 children: [{512 type: "text", text: text513 }]514 });515 }516 w.nextMatch = this.lookaheadRegExp.lastIndex;517 }518 }519},520{521 name: "wikiLink",522 match: textPrimitives.unWikiLink+"?"+textPrimitives.wikiLink,523 handler: function(w)524 {525 if(w.matchText.substr(0,1) == textPrimitives.unWikiLink) {526 w.outputText(w.output,w.matchStart+1,w.nextMatch);527 return;528 }529 if(w.matchStart > 0) {530 var preRegExp = new RegExp(textPrimitives.anyLetterStrict,"mg");531 preRegExp.lastIndex = w.matchStart-1;532 var preMatch = preRegExp.exec(w.source);533 if(preMatch.index == w.matchStart-1) {534 w.outputText(w.output,w.matchStart,w.nextMatch);535 return;536 }537 }538 if(w.autoLinkWikiWords) {539 w.output.push({540 type: "link",541 attributes: {542 to: {type: "string", value: w.matchText}543 },544 children: [{545 type: "text",546 text: w.source.substring(w.matchStart,w.nextMatch)547 }]548 });549 } else { 550 w.outputText(w.output,w.matchStart,w.nextMatch);551 }552 }553},554{555 name: "urlLink",556 match: textPrimitives.urlPattern,557 handler: function(w)558 {559 w.output.push({560 type: "element",561 tag: "a",562 attributes: {563 href: {type: "string", value: w.matchText},564 "class": {type: "string", value: "tc-tiddlylink-external"},565 target: {type: "string", value: "_blank"}566 },567 children: [{568 type: "text", text: w.source.substring(w.matchStart,w.nextMatch)569 }]570 });571 }572},573{574 name: "image",575 match: "\\[[<>]?[Ii][Mm][Gg]\\[",576 // [<] sequence below is to avoid lessThan-questionMark sequence so TiddlyWikis can be included in PHP files577 lookaheadRegExp: /\[([<]?)(>?)[Ii][Mm][Gg]\[(?:([^\|\]]+)\|)?([^\[\]\|]+)\](?:\[([^\]]*)\])?\]/mg,578 handler: function(w)579 {580 var node = {581 type: "image",582 attributes: {}583 };584 this.lookaheadRegExp.lastIndex = w.matchStart;585 var lookaheadMatch = this.lookaheadRegExp.exec(w.source),586 imageParams = {},587 linkParams = {};588 if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {589 if(lookaheadMatch[1]) {590 node.attributes.class = {type: "string", value: "classic-image-left"};591 } else if(lookaheadMatch[2]) {592 node.attributes.class = {type: "string", value: "classic-image-right"};593 }594 if(lookaheadMatch[3]) {595 node.attributes.tooltip = {type: "string", value: lookaheadMatch[3]};596 }597 node.attributes.source = {type: "string", value: lookaheadMatch[4]};598 if(lookaheadMatch[5]) {599 if(isLinkExternal(lookaheadMatch[5])) {600 w.output.push({601 type: "element",602 tag: "a",603 attributes: {604 href: {type: "string", value:lookaheadMatch[5]},605 "class": {type: "string", value: "tc-tiddlylink-external"},606 target: {type: "string", value: "_blank"}607 },608 children: [node]609 });610 } else {611 w.output.push({612 type: "link",613 attributes: {614 to: {type: "string", value: lookaheadMatch[5]}615 },616 children: [node]617 });618 }619 } else {620 w.output.push(node);621 }622 w.nextMatch = this.lookaheadRegExp.lastIndex;623 }624 }625},626{627 name: "html",628 match: "<[Hh][Tt][Mm][Ll]>",629 lookaheadRegExp: /<[Hh][Tt][Mm][Ll]>((?:.|\n)*?)<\/[Hh][Tt][Mm][Ll]>/mg,630 handler: function(w)631 {632 this.lookaheadRegExp.lastIndex = w.matchStart;633 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);634 if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {635 w.output.push({ type:"raw", html:lookaheadMatch[1]});636 w.nextMatch = this.lookaheadRegExp.lastIndex;637 }638 }639},640{641 name: "commentByBlock",642 match: "/%",643 lookaheadRegExp: /\/%((?:.|\n)*?)%\//mg,644 handler: function(w)645 {646 this.lookaheadRegExp.lastIndex = w.matchStart;647 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);648 if(lookaheadMatch && lookaheadMatch.index == w.matchStart)649 w.nextMatch = this.lookaheadRegExp.lastIndex;650 }651},652{653 name: "characterFormat",654 match: "''|//|__|\\^\\^|~~|--(?!\\s|$)|\\{\\{\\{|`",655 handler: function(w)656 {657 var e,lookaheadRegExp,lookaheadMatch;658 switch(w.matchText) {659 case "''":660 e = {type:"element",tag:"strong",children: []};661 w.output.push(e);662 w.subWikifyTerm(e.children,/('')/mg);663 break;664 case "//":665 e = {type:"element",tag:"em",children: []};666 w.output.push(e);667 w.subWikifyTerm(e.children,/(\/\/)/mg);668 break;669 case "__":670 e = {type:"element",tag:"u",children: []};671 w.output.push(e);672 w.subWikifyTerm(e.children,/(__)/mg);673 break;674 case "^^":675 e = {type:"element",tag:"sup",children: []};676 w.output.push(e);677 w.subWikifyTerm(e.children,/(\^\^)/mg);678 break;679 case "~~":680 e = {type:"element",tag:"sub",children: []};681 w.output.push(e);682 w.subWikifyTerm(e.children,/(~~)/mg);683 break;684 case "--":685 e = {type:"element",tag:"strike",children: []};686 w.output.push(e);687 w.subWikifyTerm(e.children,/(--)/mg);688 break;689 case "`":690 lookaheadRegExp = /`((?:.|\n)*?)`/mg;691 lookaheadRegExp.lastIndex = w.matchStart;692 lookaheadMatch = lookaheadRegExp.exec(w.source);693 if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {694 w.output.push({type:"element",tag:"code",695 children:[{type: "text",text: lookaheadMatch[1]}]});696 }697 break;698 case "{{{":699 lookaheadRegExp = /\{\{\{((?:.|\n)*?)\}\}\}/mg;700 lookaheadRegExp.lastIndex = w.matchStart;701 lookaheadMatch = lookaheadRegExp.exec(w.source);702 if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {703 w.output.push({type:"element",tag:"code",704 children:[{type: "text",text: lookaheadMatch[1]}]});705 w.nextMatch = lookaheadRegExp.lastIndex;706 }707 break;708 }709 }710},711{712 name: "customFormat",713 match: "@@|\\{\\{",714 handler: function(w)715 {716 switch(w.matchText) {717 case "@@":718 var e = {type:"element",tag:"span",children: []};719 w.output.push(e);720 var styles = inlineCssHelper(w);721 if(styles.length === 0)722 setAttr(e,"class","marked");723 else724 applyCssHelper(e,styles);725 w.subWikifyTerm(e.children,/(@@)/mg);726 break;727 case "{{":728 var lookaheadRegExp = /\{\{[\s]*([\-\w]+[\-\s\w]*)[\s]*\{(\n?)/mg;729 lookaheadRegExp.lastIndex = w.matchStart;730 var lookaheadMatch = lookaheadRegExp.exec(w.source);731 if(lookaheadMatch) {732 w.nextMatch = lookaheadRegExp.lastIndex;733 e = {type:"element",tag:lookaheadMatch[2] == "\n" ? "div" : "span",734 attributes: {"class": {type: "string", value:lookaheadMatch[1]}},children: []};735 w.output.push(e);736 w.subWikifyTerm(e.children,/(\}\}\})/mg);737 }738 break;739 }740 }741},742{743 name: "mdash",744 match: "--",745 handler: function(w)746 {747 w.output.push({type: "entity", entity: "&mdash;"});748 }749},750{751 name: "lineBreak",752 match: "\\n|<br ?/?>",753 handler: function(w)754 {755 w.output.push({type:"element",tag:"br"});756 }757},758{759 name: "rawText",760 match: "\"{3}|<nowiki>",761 lookaheadRegExp: /(?:\"{3}|<nowiki>)((?:.|\n)*?)(?:\"{3}|<\/nowiki>)/mg,762 handler: function(w)763 {764 this.lookaheadRegExp.lastIndex = w.matchStart;765 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);766 if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {767 w.output.push({type: "text",text: lookaheadMatch[1]768 });769 w.nextMatch = this.lookaheadRegExp.lastIndex;770 }771 }772},773{774 name: "htmlEntitiesEncoding",775 match: "&#?[a-zA-Z0-9]{2,8};",776 handler: function(w)777 {778 w.output.push({type: "entity", entity: w.matchText});779 }780}781];782exports.rules = rules;...

Full Screen

Full Screen

Formatter.js

Source:Formatter.js Github

copy

Full Screen

1//--2//-- Standard formatters3//--4config.formatters = [5{6 name: "table",7 match: "^\\|(?:[^\\n]*)\\|(?:[fhck]?)$",8 lookaheadRegExp: /^\|([^\n]*)\|([fhck]?)$/mg,9 rowTermRegExp: /(\|(?:[fhck]?)$\n?)/mg,10 cellRegExp: /(?:\|([^\n\|]*)\|)|(\|[fhck]?$\n?)/mg,11 cellTermRegExp: /((?:\x20*)\|)/mg,12 rowTypes: {"c":"caption", "h":"thead", "":"tbody", "f":"tfoot"},13 handler: function(w)14 {15 var table = createTiddlyElement(w.output,"table",null,"twtable");16 var prevColumns = [];17 var currRowType = null;18 var rowContainer;19 var rowCount = 0;20 var onmouseover = function() {jQuery(this).addClass("hoverRow");};21 var onmouseout = function() {jQuery(this).removeClass("hoverRow");};22 w.nextMatch = w.matchStart;23 this.lookaheadRegExp.lastIndex = w.nextMatch;24 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);25 while(lookaheadMatch && lookaheadMatch.index == w.nextMatch) {26 var nextRowType = lookaheadMatch[2];27 if(nextRowType == "k") {28 table.className = lookaheadMatch[1];29 w.nextMatch += lookaheadMatch[0].length+1;30 } else {31 if(nextRowType != currRowType) {32 rowContainer = createTiddlyElement(table,this.rowTypes[nextRowType]);33 currRowType = nextRowType;34 }35 if(currRowType == "c") {36 // Caption37 w.nextMatch++;38 if(rowContainer != table.firstChild)39 table.insertBefore(rowContainer,table.firstChild);40 rowContainer.setAttribute("align",rowCount == 0?"top":"bottom");41 w.subWikifyTerm(rowContainer,this.rowTermRegExp);42 } else {43 var theRow = createTiddlyElement(rowContainer,"tr",null,rowCount%2?"oddRow":"evenRow");44 theRow.onmouseover = onmouseover;45 theRow.onmouseout = onmouseout;46 this.rowHandler(w,theRow,prevColumns);47 rowCount++;48 }49 }50 this.lookaheadRegExp.lastIndex = w.nextMatch;51 lookaheadMatch = this.lookaheadRegExp.exec(w.source);52 }53 },54 rowHandler: function(w,e,prevColumns)55 {56 var col = 0;57 var colSpanCount = 1;58 var prevCell = null;59 this.cellRegExp.lastIndex = w.nextMatch;60 var cellMatch = this.cellRegExp.exec(w.source);61 while(cellMatch && cellMatch.index == w.nextMatch) {62 if(cellMatch[1] == "~") {63 // Rowspan64 var last = prevColumns[col];65 if(last) {66 last.rowSpanCount++;67 last.element.setAttribute("rowspan",last.rowSpanCount);68 last.element.setAttribute("rowSpan",last.rowSpanCount); // Needed for IE69 last.element.valign = "center";70 if(colSpanCount > 1) {71 last.element.setAttribute("colspan",colSpanCount);72 last.element.setAttribute("colSpan",colSpanCount); // Needed for IE73 colSpanCount = 1;74 }75 }76 w.nextMatch = this.cellRegExp.lastIndex-1;77 } else if(cellMatch[1] == ">") {78 // Colspan79 colSpanCount++;80 w.nextMatch = this.cellRegExp.lastIndex-1;81 } else if(cellMatch[2]) {82 // End of row83 if(prevCell && colSpanCount > 1) {84 prevCell.setAttribute("colspan",colSpanCount);85 prevCell.setAttribute("colSpan",colSpanCount); // Needed for IE86 }87 w.nextMatch = this.cellRegExp.lastIndex;88 break;89 } else {90 // Cell91 w.nextMatch++;92 var styles = config.formatterHelpers.inlineCssHelper(w);93 var spaceLeft = false;94 var chr = w.source.substr(w.nextMatch,1);95 while(chr == " ") {96 spaceLeft = true;97 w.nextMatch++;98 chr = w.source.substr(w.nextMatch,1);99 }100 var cell;101 if(chr == "!") {102 cell = createTiddlyElement(e,"th");103 w.nextMatch++;104 } else {105 cell = createTiddlyElement(e,"td");106 }107 prevCell = cell;108 prevColumns[col] = {rowSpanCount:1,element:cell};109 if(colSpanCount > 1) {110 cell.setAttribute("colspan",colSpanCount);111 cell.setAttribute("colSpan",colSpanCount); // Needed for IE112 colSpanCount = 1;113 }114 config.formatterHelpers.applyCssHelper(cell,styles);115 w.subWikifyTerm(cell,this.cellTermRegExp);116 if(w.matchText.substr(w.matchText.length-2,1) == " ") // spaceRight117 cell.align = spaceLeft ? "center" : "left";118 else if(spaceLeft)119 cell.align = "right";120 w.nextMatch--;121 }122 col++;123 this.cellRegExp.lastIndex = w.nextMatch;124 cellMatch = this.cellRegExp.exec(w.source);125 }126 }127},128{129 name: "heading",130 match: "^!{1,6}",131 termRegExp: /(\n)/mg,132 handler: function(w)133 {134 w.subWikifyTerm(createTiddlyElement(w.output,"h" + w.matchLength),this.termRegExp);135 }136},137{138 name: "list",139 match: "^(?:[\\*#;:]+)",140 lookaheadRegExp: /^(?:(?:(\*)|(#)|(;)|(:))+)/mg,141 termRegExp: /(\n)/mg,142 handler: function(w)143 {144 var stack = [w.output];145 var currLevel = 0, currType = null;146 var listLevel, listType, itemType, baseType;147 w.nextMatch = w.matchStart;148 this.lookaheadRegExp.lastIndex = w.nextMatch;149 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);150 while(lookaheadMatch && lookaheadMatch.index == w.nextMatch) {151 if(lookaheadMatch[1]) {152 listType = "ul";153 itemType = "li";154 } else if(lookaheadMatch[2]) {155 listType = "ol";156 itemType = "li";157 } else if(lookaheadMatch[3]) {158 listType = "dl";159 itemType = "dt";160 } else if(lookaheadMatch[4]) {161 listType = "dl";162 itemType = "dd";163 }164 if(!baseType)165 baseType = listType;166 listLevel = lookaheadMatch[0].length;167 w.nextMatch += lookaheadMatch[0].length;168 var t;169 if(listLevel > currLevel) {170 for(t=currLevel; t<listLevel; t++) {171 var target = (currLevel == 0) ? stack[stack.length-1] : stack[stack.length-1].lastChild;172 stack.push(createTiddlyElement(target,listType));173 }174 } else if(listType!=baseType && listLevel==1) {175 w.nextMatch -= lookaheadMatch[0].length;176 return;177 } else if(listLevel < currLevel) {178 for(t=currLevel; t>listLevel; t--)179 stack.pop();180 } else if(listLevel == currLevel && listType != currType) {181 stack.pop();182 stack.push(createTiddlyElement(stack[stack.length-1].lastChild,listType));183 }184 currLevel = listLevel;185 currType = listType;186 var e = createTiddlyElement(stack[stack.length-1],itemType);187 w.subWikifyTerm(e,this.termRegExp);188 this.lookaheadRegExp.lastIndex = w.nextMatch;189 lookaheadMatch = this.lookaheadRegExp.exec(w.source);190 }191 }192},193{194 name: "quoteByBlock",195 match: "^<<<\\n",196 termRegExp: /(^<<<(\n|$))/mg,197 element: "blockquote",198 handler: config.formatterHelpers.createElementAndWikify199},200{201 name: "quoteByLine",202 match: "^>+",203 lookaheadRegExp: /^>+/mg,204 termRegExp: /(\n)/mg,205 element: "blockquote",206 handler: function(w)207 {208 var stack = [w.output];209 var currLevel = 0;210 var newLevel = w.matchLength;211 var t,matched;212 do {213 if(newLevel > currLevel) {214 for(t=currLevel; t<newLevel; t++)215 stack.push(createTiddlyElement(stack[stack.length-1],this.element));216 } else if(newLevel < currLevel) {217 for(t=currLevel; t>newLevel; t--)218 stack.pop();219 }220 currLevel = newLevel;221 w.subWikifyTerm(stack[stack.length-1],this.termRegExp);222 createTiddlyElement(stack[stack.length-1],"br");223 this.lookaheadRegExp.lastIndex = w.nextMatch;224 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);225 matched = lookaheadMatch && lookaheadMatch.index == w.nextMatch;226 if(matched) {227 newLevel = lookaheadMatch[0].length;228 w.nextMatch += lookaheadMatch[0].length;229 }230 } while(matched);231 }232},233{234 name: "rule",235 match: "^----+$\\n?|<hr ?/?>\\n?",236 handler: function(w)237 {238 createTiddlyElement(w.output,"hr");239 }240},241{242 name: "monospacedByLine",243 match: "^(?:/\\*\\{\\{\\{\\*/|\\{\\{\\{|//\\{\\{\\{|<!--\\{\\{\\{-->)\\n",244 element: "pre",245 handler: function(w)246 {247 switch(w.matchText) {248 case "/*{{{*/\n": // CSS249 this.lookaheadRegExp = /\/\*\{\{\{\*\/\n*((?:^[^\n]*\n)+?)(\n*^\f*\/\*\}\}\}\*\/$\n?)/mg;250 break;251 case "{{{\n": // monospaced block252 this.lookaheadRegExp = /^\{\{\{\n((?:^[^\n]*\n)+?)(^\f*\}\}\}$\n?)/mg;253 break;254 case "//{{{\n": // plugin255 this.lookaheadRegExp = /^\/\/\{\{\{\n\n*((?:^[^\n]*\n)+?)(\n*^\f*\/\/\}\}\}$\n?)/mg;256 break;257 case "<!--{{{-->\n": //template258 this.lookaheadRegExp = /<!--\{\{\{-->\n*((?:^[^\n]*\n)+?)(\n*^\f*<!--\}\}\}-->$\n?)/mg;259 break;260 default:261 break;262 }263 config.formatterHelpers.enclosedTextHelper.call(this,w);264 }265},266{267 name: "wikifyComment",268 match: "^(?:/\\*\\*\\*|<!---)\\n",269 handler: function(w)270 {271 var termRegExp = (w.matchText == "/***\n") ? (/(^\*\*\*\/\n)/mg) : (/(^--->\n)/mg);272 w.subWikifyTerm(w.output,termRegExp);273 }274},275{276 name: "macro",277 match: "<<",278 lookaheadRegExp: /<<([^>\s]+)(?:\s*)((?:[^>]|(?:>(?!>)))*)>>/mg,279 handler: function(w)280 {281 this.lookaheadRegExp.lastIndex = w.matchStart;282 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);283 if(lookaheadMatch && lookaheadMatch.index == w.matchStart && lookaheadMatch[1]) {284 w.nextMatch = this.lookaheadRegExp.lastIndex;285 invokeMacro(w.output,lookaheadMatch[1],lookaheadMatch[2],w,w.tiddler);286 }287 }288},289{290 name: "prettyLink",291 match: "\\[\\[",292 lookaheadRegExp: /\[\[(.*?)(?:\|(~)?(.*?))?\]\]/mg,293 handler: function(w)294 {295 this.lookaheadRegExp.lastIndex = w.matchStart;296 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);297 if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {298 var e;299 var text = lookaheadMatch[1];300 if(lookaheadMatch[3]) {301 // Pretty bracketted link302 var link = lookaheadMatch[3];303 e = (!lookaheadMatch[2] && config.formatterHelpers.isExternalLink(link)) ?304 createExternalLink(w.output,link) : createTiddlyLink(w.output,link,false,null,w.isStatic,w.tiddler);305 } else {306 // Simple bracketted link307 e = createTiddlyLink(w.output,text,false,null,w.isStatic,w.tiddler);308 }309 createTiddlyText(e,text);310 w.nextMatch = this.lookaheadRegExp.lastIndex;311 }312 }313},314{315 name: "wikiLink",316 match: config.textPrimitives.unWikiLink+"?"+config.textPrimitives.wikiLink,317 handler: function(w)318 {319 if(w.matchText.substr(0,1) == config.textPrimitives.unWikiLink) {320 w.outputText(w.output,w.matchStart+1,w.nextMatch);321 return;322 }323 if(w.matchStart > 0) {324 var preRegExp = new RegExp(config.textPrimitives.anyLetterStrict,"mg");325 preRegExp.lastIndex = w.matchStart-1;326 var preMatch = preRegExp.exec(w.source);327 if(preMatch.index == w.matchStart-1) {328 w.outputText(w.output,w.matchStart,w.nextMatch);329 return;330 }331 }332 if(w.autoLinkWikiWords || store.isShadowTiddler(w.matchText)) {333 var link = createTiddlyLink(w.output,w.matchText,false,null,w.isStatic,w.tiddler);334 w.outputText(link,w.matchStart,w.nextMatch);335 } else {336 w.outputText(w.output,w.matchStart,w.nextMatch);337 }338 }339},340{341 name: "urlLink",342 match: config.textPrimitives.urlPattern,343 handler: function(w)344 {345 w.outputText(createExternalLink(w.output,w.matchText),w.matchStart,w.nextMatch);346 }347},348{349 name: "image",350 match: "\\[[<>]?[Ii][Mm][Gg]\\[",351 //# [<] sequence below is to avoid lessThan-questionMark sequence so TiddlyWikis can be included in PHP files352 lookaheadRegExp: /\[([<]?)(>?)[Ii][Mm][Gg]\[(?:([^\|\]]+)\|)?([^\[\]\|]+)\](?:\[([^\]]*)\])?\]/mg,353 handler: function(w)354 {355 this.lookaheadRegExp.lastIndex = w.matchStart;356 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);357 if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {358 var e = w.output;359 if(lookaheadMatch[5]) {360 var link = lookaheadMatch[5];361 e = config.formatterHelpers.isExternalLink(link) ? createExternalLink(w.output,link) : createTiddlyLink(w.output,link,false,null,w.isStatic,w.tiddler);362 jQuery(e).addClass("imageLink");363 }364 var img = createTiddlyElement(e,"img");365 if(lookaheadMatch[1])366 img.align = "left";367 else if(lookaheadMatch[2])368 img.align = "right";369 if(lookaheadMatch[3]) {370 img.title = lookaheadMatch[3];371 img.setAttribute("alt",lookaheadMatch[3]);372 }373 img.src = lookaheadMatch[4];374 w.nextMatch = this.lookaheadRegExp.lastIndex;375 }376 }377},378{379 name: "html",380 match: "<[Hh][Tt][Mm][Ll]>",381 lookaheadRegExp: /<[Hh][Tt][Mm][Ll]>((?:.|\n)*?)<\/[Hh][Tt][Mm][Ll]>/mg,382 handler: function(w)383 {384 this.lookaheadRegExp.lastIndex = w.matchStart;385 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);386 if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {387 createTiddlyElement(w.output,"span").innerHTML = lookaheadMatch[1];388 w.nextMatch = this.lookaheadRegExp.lastIndex;389 }390 }391},392{393 name: "commentByBlock",394 match: "/%",395 lookaheadRegExp: /\/%((?:.|\n)*?)%\//mg,396 handler: function(w)397 {398 this.lookaheadRegExp.lastIndex = w.matchStart;399 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);400 if(lookaheadMatch && lookaheadMatch.index == w.matchStart)401 w.nextMatch = this.lookaheadRegExp.lastIndex;402 }403},404{405 name: "characterFormat",406 match: "''|//|__|\\^\\^|~~|--(?!\\s|$)|\\{\\{\\{",407 handler: function(w)408 {409 switch(w.matchText) {410 case "''":411 w.subWikifyTerm(w.output.appendChild(document.createElement("strong")),/('')/mg);412 break;413 case "//":414 w.subWikifyTerm(createTiddlyElement(w.output,"em"),/(\/\/)/mg);415 break;416 case "__":417 w.subWikifyTerm(createTiddlyElement(w.output,"u"),/(__)/mg);418 break;419 case "^^":420 w.subWikifyTerm(createTiddlyElement(w.output,"sup"),/(\^\^)/mg);421 break;422 case "~~":423 w.subWikifyTerm(createTiddlyElement(w.output,"sub"),/(~~)/mg);424 break;425 case "--":426 w.subWikifyTerm(createTiddlyElement(w.output,"strike"),/(--)/mg);427 break;428 case "{{{":429 var lookaheadRegExp = /\{\{\{((?:.|\n)*?)\}\}\}/mg;430 lookaheadRegExp.lastIndex = w.matchStart;431 var lookaheadMatch = lookaheadRegExp.exec(w.source);432 if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {433 createTiddlyElement(w.output,"code",null,null,lookaheadMatch[1]);434 w.nextMatch = lookaheadRegExp.lastIndex;435 }436 break;437 }438 }439},440{441 name: "customFormat",442 match: "@@|\\{\\{",443 handler: function(w)444 {445 switch(w.matchText) {446 case "@@":447 var e = createTiddlyElement(w.output,"span");448 var styles = config.formatterHelpers.inlineCssHelper(w);449 if(styles.length == 0)450 e.className = "marked";451 else452 config.formatterHelpers.applyCssHelper(e,styles);453 w.subWikifyTerm(e,/(@@)/mg);454 break;455 case "{{":456 var lookaheadRegExp = /\{\{[\s]*([\w]+[\s\w]*)[\s]*\{(\n?)/mg;457 lookaheadRegExp.lastIndex = w.matchStart;458 var lookaheadMatch = lookaheadRegExp.exec(w.source);459 if(lookaheadMatch) {460 w.nextMatch = lookaheadRegExp.lastIndex;461 e = createTiddlyElement(w.output,lookaheadMatch[2] == "\n" ? "div" : "span",null,lookaheadMatch[1]);462 w.subWikifyTerm(e,/(\}\}\})/mg);463 }464 break;465 }466 }467},468{469 name: "mdash",470 match: "--",471 handler: function(w)472 {473 createTiddlyElement(w.output,"span").innerHTML = "&mdash;";474 }475},476{477 name: "lineBreak",478 match: "\\n|<br ?/?>",479 handler: function(w)480 {481 createTiddlyElement(w.output,"br");482 }483},484{485 name: "rawText",486 match: "\"{3}|<nowiki>",487 lookaheadRegExp: /(?:\"{3}|<nowiki>)((?:.|\n)*?)(?:\"{3}|<\/nowiki>)/mg,488 handler: function(w)489 {490 this.lookaheadRegExp.lastIndex = w.matchStart;491 var lookaheadMatch = this.lookaheadRegExp.exec(w.source);492 if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {493 createTiddlyElement(w.output,"span",null,null,lookaheadMatch[1]);494 w.nextMatch = this.lookaheadRegExp.lastIndex;495 }496 }497},498{499 name: "htmlEntitiesEncoding",500 match: "(?:(?:&#?[a-zA-Z0-9]{2,8};|.)(?:&#?(?:x0*(?:3[0-6][0-9a-fA-F]|1D[c-fC-F][0-9a-fA-F]|20[d-fD-F][0-9a-fA-F]|FE2[0-9a-fA-F])|0*(?:76[89]|7[7-9][0-9]|8[0-7][0-9]|761[6-9]|76[2-7][0-9]|84[0-3][0-9]|844[0-7]|6505[6-9]|6506[0-9]|6507[0-1]));)+|&#?[a-zA-Z0-9]{2,8};)",501 handler: function(w)502 {503 createTiddlyElement(w.output,"span").innerHTML = w.matchText;504 }505}...

Full Screen

Full Screen

parser.js

Source:parser.js Github

copy

Full Screen

1Object.constructor.prototype.error = function(message, t) {2 t = t || this;3 t.name = "SyntaxError";4 t.message = message;5 throw treturn;6};7RegExp.prototype.bexec = function(str) {8 var i, m;9 i = this.lastIndex;10 m = this.exec(str);11 if (m && m.index === i) {12 return m;13 }14 return null;15};16String.prototype.tokens = function() {17 var RESERVED_WORD, from, getTok, i, key, m, make, n, result, rw, tokens, value;18 from = void 0;19 i = 0;20 n = void 0;21 m = void 0;22 result = [];23 tokens = {24 WHITES: /\s+/g,25 ID: /[a-zA-Z_]\w*/g,26 NUM: /\b\d+(\.\d*)?([eE][+-]?\d+)?\b/g,27 STRING: /('(\\.|[^'])*'|"(\\.|[^"])*")/g,28 ONELINECOMMENT: /\/\/.*/g,29 MULTIPLELINECOMMENT: /\/[*](.|\n)*?[*]\//g,30 COMPARISONOPERATOR: /[<>=!]=|[<>]/g,31 ONECHAROPERATORS: /([=()&|;:,{}[\]])/g,32 ADDOP: /[+-]/g,33 MULTOP: /[*\/]/g34 };35 RESERVED_WORD = {36 p: "P",37 "if": "IF",38 then: "THEN"39 };40 make = function(type, value) {41 return {42 type: type,43 value: value,44 from: from,45 to: i46 };47 };48 getTok = function() {49 var str;50 str = m[0];51 i += str.length;52 return str;53 };54 if (!this) {55 return;56 }57 while (i < this.length) {58 for (key in tokens) {59 value = tokens[key];60 value.lastIndex = i;61 }62 from = i;63 if (m = tokens.WHITES.bexec(this) || (m = tokens.ONELINECOMMENT.bexec(this)) || (m = tokens.MULTIPLELINECOMMENT.bexec(this))) {64 getTok();65 } else if (m = tokens.ID.bexec(this)) {66 rw = RESERVED_WORD[m[0]];67 if (rw) {68 result.push(make(rw, getTok()));69 } else {70 result.push(make("ID", getTok()));71 }72 } else if (m = tokens.NUM.bexec(this)) {73 n = +getTok();74 if (isFinite(n)) {75 result.push(make("NUM", n));76 } else {77 make("NUM", m[0]).error("Bad number");78 }79 } else if (m = tokens.STRING.bexec(this)) {80 result.push(make("STRING", getTok().replace(/^["']|["']$/g, "")));81 } else if (m = tokens.COMPARISONOPERATOR.bexec(this)) {82 result.push(make("COMPARISON", getTok()));83 } else if (m = tokens.ADDOP.bexec(this)) {84 result.push(make("ADDOP", getTok()));85 } else if (m = tokens.MULTOP.bexec(this)) {86 result.push(make("MULTOP", getTok()));87 } else if (m = tokens.ONECHAROPERATORS.bexec(this)) {88 result.push(make(m[0], getTok()));89 } else {90 throw "Syntax error near '" + (this.substr(i)) + "'";91 }92 }93 return result;94};95var parse = function(input) {96 var condition, expression, factor, lookahead, match, statement, statements, term, tokens, tree;97 tokens = input.tokens();98 lookahead = tokens.shift();99 match = function(t) {100 if (lookahead.type === t) {101 lookahead = tokens.shift();102 if (typeof lookahead === "undefined") {103 lookahead = null;104 }105 } else {106 throw ("Syntax Error. Expected " + t + " found '") + lookahead.value + "' near '" + input.substr(lookahead.from) + "'";107 }108 };109programm = function(){110 var result;111 result = block;112 match(".");113 return result;114}115block = function() {116 var result, left, right;117 if (lookahead && lookahead.value === "const") {118 match("const");119 left = {120 type: "ID",121 value: lookahead.value122 };123 match("ID");124 match("=");125 right = lookahead.value;126 match("NUM");127 result = {128 type: "=",129 left: left,130 right: right131 };132 while (lookahead && lookahead.value === "const") {133 match("const");134 result = {135 type: "ID",136 value: lookahead.value137 };138 match("ID");139 match("=");140 right = lookahead.value;141 match("NUM");142 result = {143 type: "=",144 left: left,145 right: right146 };147 }148 match(";");149 };150 else if (lookahead && lookahead.value === "var") {151 match("var");152 result = {153 type: "ID",154 value: lookahead.value155 };156 match("ID");157 while (lookahead && lookahead.value === ",") {158 match(",");159 result = {160 type: "ID",161 value: lookahead.value162 };163 match("ID");164 }165 match(";");166 };167 else if (lookahead && lookahead.value === "procedure")168 while (lookahead && lookahead.value === "procedure") {169 match("procedure");170 result = {171 type: "ID",172 value: lookahead.value173 };174 match("ID");175 match("(");176 while (lookahead && lookahead.value === "var"){177 match("var");178 result = {179 type: "ID",180 value: lookahead.value181 };182 }183 match(")");184 left = block();185 }186 right = statement();187 result = {188 type: "block",189 left: left,190 right: right191 };192 return result;193}194statement = function(){195 var result, right, left;196 if (lookahead && lookahead.type === "ID") {197 left = {198 type: "ID",199 value: lookahead.value200 };201 match("ID");202 match("=");203 right = expression();204 result = {205 type: "=",206 left: left,207 right: right208 };209 };210 else if(lookahead && lookahead.value === "call") {211 match("call");212 result = {213 type: "ID",214 value: lookahead.value215 };216 match("ID")217 };218 else if(lookahead && lookahead.value === "begin") {219 match("begin");220 result = statement();221 while (lookahead && lookahead.value === ";") {222 match(";");223 result = statement();224 }225 match("end");226 };227 else if(lookahead && lookahead.value === "if") {228 match("if");229 left = condition();230 match("then");231 right = statement();232 result = {233 type: "statement",234 left: left,235 right: right236 };237 if(lookahead && lookahead.value === "else"){238 match("else");239 result = statement();240 };241 };242 else if(lookahead && lookahead.value === "while") {243 match("while");244 left = condition();245 match("do");246 right = statement();247 result = {248 type: "statement",249 left: left,250 right: right251 };252 };253 return rasult;254}255condition(){256 var result, right, left, type;257 left = expression();258 type = lookahead.value;259 match("COMPARISON");260 right = expression();261 result = {262 type: type,263 left: left,264 right: right265 };266 return result;267}268 expression = function() {269 var result, right, type;270 result = term();271 while (lookahead && lookahead.type === "ADDOP") {272 type = lookahead.value;273 match("ADDOP");274 right = term();275 result = {276 type: type,277 left: result,278 right: right279 };280 }281 return result;282 };283 term = function() {284 var result, right, type;285 result = factor();286 if (lookahead && lookahead.type === "MULTOP") {287 type = lookahead.value;288 match("MULTOP");289 right = term();290 result = {291 type: type,292 left: result,293 right: right294 };295 }296 return result;297};298 factor = function() {299 var result;300 result = null;301 if (lookahead.type === "ID") {302 result = {303 type: "ID",304 value: lookahead.value305 }306 match("ID");307 };308 else if (lookahead.type === "NUM") {309 result = {310 type: "NUM",311 value: lookahead.value312 };313 match("NUM");314 } else if (lookahead.type === "(") {315 match("(");316 result = expression();317 match(")");318 } else {319 throw "Syntax Error. Expected number or identifier or '(' but found " + (lookahead ? lookahead.value : "end of input") + " near '" + input.substr(lookahead.from) + "'";320 }321 return result;322 };323 tree = expression(input);324 if (lookahead != null) {325 throw "Syntax Error parsing statements. " + "Expected 'end of input' and found '" + input.substr(lookahead.from) + "'";326 }327 return tree;...

Full Screen

Full Screen

T10003903.js

Source:T10003903.js Github

copy

Full Screen

...43 default: return (false);44 }45}4647function move_lookahead()48{49 i = i + 1;5051 if(i - 1 == document.frmEditor.Texto.value.length)52 {53 return "#";54 }55 else56 {57 return document.frmEditor.Texto.value.substr(i - 1, 1).toUpperCase();58 }59}6061function BuscaProximoToken()62{63 token = "";6465 while(lookahead == " " || lookahead.charCodeAt(0) == 10 || lookahead.charCodeAt(0) == 13 || lookahead.charCodeAt(0) == 9)66 lookahead = move_lookahead();6768 if(Letra(lookahead))69 {70 token = lookahead;71 lookahead = move_lookahead();7273 while(Letra(lookahead) || Numero(lookahead) || lookahead == "_")74 {75 token = token + lookahead;76 lookahead = move_lookahead();77 }78 79 if(token == "VARIAVEIS")80 tipo_token = "T_VARIAVEIS ";81 else82 if(token == "INICIO")83 tipo_token = "T_INICIO ";84 else85 if(token == "FIM")86 tipo_token = "T_FIM ";87 else88 if(token == "ESCREVA")89 tipo_token = "T_ESCREVA ";90 else91 tipo_token = "T_ID ";92 }93 else94 {95 if(Numero(lookahead))96 {97 token = "";98 while(Numero(lookahead))99 {100 token = token + lookahead;101 lookahead = move_lookahead();102 }103 104 tipo_token = "T_NUMERO ";105 }106 else107 {108 switch(lookahead)109 {110 case ",": token = lookahead;111 lookahead = move_lookahead();112 tipo_token = "T_VIRGULA ";113 break;114115 case ";": token = lookahead;116 lookahead = move_lookahead();117 tipo_token = "T_PONTO_VIRGULA ";118 break;119120 case "+": token = lookahead;121 lookahead = move_lookahead();122 tipo_token = "T_MAIS ";123 break;124125 case "-": token = lookahead;126 lookahead = move_lookahead();127 tipo_token = "T_MENOS ";128 break;129130 case "*": token = lookahead;131 lookahead = move_lookahead();132 tipo_token = "T_VEZES ";133 break;134135 case "/": token = lookahead;136 lookahead = move_lookahead();137 tipo_token = "T_SOBRE ";138 break;139140 case "(": token = lookahead;141 lookahead = move_lookahead();142 tipo_token = "T_ABREPAR ";143 break;144145 case ")": token = lookahead;146 lookahead = move_lookahead();147 tipo_token = "T_FECHAPAR ";148 break;149150 case ":": token = lookahead;151 lookahead = move_lookahead();152 if(lookahead == "=")153 {154 token = token + lookahead;155 lookahead = move_lookahead();156 tipo_token = "T_ATRIBUICAO ";157 }158 else159 tipo_token = "T_DOIS_PONTOS ";160 break;161162 case "=": token = lookahead;163 lookahead = move_lookahead();164 tipo_token = "T_IGUAL ";165 break;166167 case "<": token = lookahead;168 lookahead = move_lookahead();169 if(lookahead == "=")170 {171 token = token + lookahead;172 lookahead = move_lookahead();173 tipo_token = "T_MENOR_IGUAL ";174 }175 else176 if(lookahead == ">")177 {178 token = token + lookahead;179 lookahead = move_lookahead();180 tipo_token = "T_DIFERENTE ";181 }182 else183 tipo_token = "T_MENOR ";184 break;185186 case ">": token = lookahead;187 lookahead = move_lookahead();188 if(lookahead == "=")189 {190 token = token + lookahead;191 lookahead = move_lookahead();192 tipo_token = "T_MAIOR_IGUAL ";193 }194 else195 tipo_token = "T_MAIOR ";196 break;197198 case "#": token = lookahead;199 lookahead = move_lookahead();200 tipo_token = "T_FIM_FONTE ";201 break;202203 default: token = lookahead;204 lookahead = move_lookahead();205 while(lookahead != " " && lookahead != "#" && lookahead.charCodeAt(0) != 10 && lookahead.charCodeAt(0) != 13 && lookahead.charCodeAt(0) != 9)206 {207 token = token + lookahead;208 lookahead = move_lookahead();209 }210 tipo_token = "T_ERRO_LEXICO ";211 }212 }213 }214}215216function Analisa()217{218 var resultado = "";219220 i = 0;221222 lookahead = move_lookahead();223 BuscaProximoToken();224 while(tipo_token != "T_FIM_FONTE ")225 {226 resultado = resultado + "<br>Token encontrado: " + tipo_token + " -> '" + token + "'";227 BuscaProximoToken();228 }229 resultado = resultado + "<br>Token encontrado: " + tipo_token + " -> '" + token + "'";230231 //document.write("Resultado da an�lise:<BR><PRE>" + resultado + "</PRE>"); 232 document.getElementById('resultado').innerHTML = resultado; ...

Full Screen

Full Screen

DynamicParser.js

Source:DynamicParser.js Github

copy

Full Screen

1const Associativity = require("./Associativity").Associativity;2const OP = 0;3const ASSOCIATIVITY = 1;4const PRIORITY = 2;5const enableLogging = false;6function log(...args) {7 if (enableLogging) {8 console.log("Parser: ", ...args)9 }10}11function DynamicParser(input) {12 const _operators = {}; // map<string, map<assoc, int>>13 let _input = input;14 let _lexer = input.tokenSource;15 this.isAnonymous = function (token) {16 return ((token.length === 1) && (token[0] === '_')) || ((token.text.length === 1) && (token.text[0] === '_'))17 };18 this.getOperatorPriority = function (operator, associativity) {19 const functor = operator.text || operator;20 if (functor in _operators) {21 const assocPriority = _operators[functor];22 if (associativity in assocPriority) {23 return assocPriority[associativity];24 }25 }26 return 1201;27 };28 this.isOperator = function (operator) {29 return _lexer.isOperator(operator);30 };31 this.addOperator = function (functor, associativity, priority) {32 _lexer.addOperators(functor);33 if (!(functor in _operators)) {34 _operators[functor] = {}35 }36 const assocPriority = _operators[functor];37 assocPriority[associativity] = priority;38 };39 this.isOperatorAssociativity = function (operator, associativity) {40 const functor = operator.text || operator;41 if (functor in _operators) {42 return associativity in _operators[functor];43 }44 return false45 };46 this.mustBeExcluded = function (lookahead, except) {47 for (const e of except) {48 if (this.isOperator(e) && lookahead.text === e) {49 return true;50 }51 }52 return false;53 };54 this.lookaheadFunc = function (f, associativity, priority, except) {55 const lookahead = _input.LT(1);56 log("lookahead: " + lookahead);57 if (!this.isOperator(lookahead.text)) {58 return null;59 }60 if (this.mustBeExcluded(lookahead, except)) {61 return null;62 }63 if (!this.isOperatorAssociativity(lookahead, associativity)) {64 return null;65 }66 return f(this.getOperatorPriority(lookahead, associativity), priority);67 };68 this.lookaheadIs = function (associativity, except) {69 let associativities;70 if (associativity.__proto__ !== Array.prototype) {71 associativities = [associativity];72 } else {73 associativities = associativity;74 }75 const lookahead = _input.LT(1);76 if (this.mustBeExcluded(lookahead, except || [])) {77 return false;78 }79 for (const a of associativities) {80 if (this.isOperatorAssociativity(lookahead, a)) {81 return true;82 }83 }84 return false;85 };86 const _compare = function (x, y) {87 return (x < y) ? -1 : ((x === y) ? 0 : 1);88 };89 this.lookaheadGt = function (associativity, priority, except) {90 let res = this.lookaheadFunc(_compare, associativity, priority, except);91 if (res === null)92 res = -1;93 return res > 0;94 };95 this.lookaheadEq = function (associativity, priority, except) {96 let res = this.lookaheadFunc(_compare, associativity, priority, except);97 if (res === null)98 res = -1;99 return res === 0;100 };101 this.lookaheadNeq = function (associativity, priority, except) {102 let res = this.lookaheadFunc(_compare, associativity, priority, except);103 if (res === null)104 res = 0;105 return res !== 0;106 };107 this.lookaheadGeq = function (associativity, priority, except) {108 let res = this.lookaheadFunc(_compare, associativity, priority, except);109 if (res === null)110 res = -1;111 return res >= 0;112 };113 this.lookaheadLeq = function (associativity, priority, except) {114 let res = this.lookaheadFunc(_compare, associativity, priority, except);115 if (res === null)116 res = 1;117 return res <= 0;118 };119 this.lookaheadLt = function (associativity, priority, except) {120 let res = this.lookaheadFunc(_compare, associativity, priority, except);121 if (res === null)122 res = 1;123 return res < 0;124 };125 this.lookahead = function (associativity, top, bottom, except) {126 let associativities;127 if (associativity.__proto__ !== Array.prototype) {128 associativities = [associativity];129 } else {130 associativities = associativity;131 }132 const lookahead = _input.LT(1);133 if (this.mustBeExcluded(lookahead, except)) {134 return false;135 }136 for (const a of associativities) {137 if (this.isOperatorAssociativity(lookahead, a)) {138 const priority = this.getOperatorPriority(lookahead, a);139 if (priority <= top && priority >= bottom) {140 return true;141 }142 }143 }144 return false;145 }146}...

Full Screen

Full Screen

parse.js

Source:parse.js Github

copy

Full Screen

1const inspect = require("util").inspect;2let ins = (x) => inspect(x, {depth:null});3let fs = require("fs");4const WHITES = /^(\s|[#;].*|\/\*(.|\n)*?\*\/)*/;5const STRING = /^"((?:[^"\\]|\\.)*)"/;6const NUMBER = /^([-+]?\d*\.?\d+([eE][-+]?\d+)?)/;7const WORD = /^([^\s(),"]+)/; // No se niega el dígito ni el signo8const LP = /^([(])/;9const RP = /^\)/;10const COMMA = /^(,)/;11const NEWLINE = /\r\n|\r|\n/;12let program;13let lookahead;14let lineno = 1;15let setProgram = function(prg) {16 program = prg;17 lineno = 1;18 return {program, lineno}19};20let getProgram = function() {21 return {program, lineno}22};23function lex() {24 let match;25 match = WHITES.exec(program);26 if (NEWLINE.test(match[0])) {27 lineno += match[0].split(NEWLINE).length-1;28 }29 program = program.slice(match[0].length);30 if (program.length > 0) {31 if (match = STRING.exec(program)) {32 lookahead = { type: "STRING", value: match[1]}33 } else if (match = NUMBER.exec(program)) {34 lookahead = {type: "NUMBER", value: Number(match[1])};35 } else if (match = LP.exec(program)) { 36 lookahead = {type: "LP", value: match[1]};37 } else if (match = COMMA.exec(program)) {38 lookahead = {type: "COMMA", value: match[1]};39 } else if (match = RP.exec(program)) {40 lookahead = {type: "RP", value: match[0]};41 } else if (match = WORD.exec(program)) {42 lookahead = {type: "WORD", value: match[1]};43 } else {44 throw new SyntaxError(`Unexpect syntax line ${lineno}: ${program.slice(0,10)}`);45 }46 program = program.slice(match[0].length);47 }48 else {49 lookahead = null; // End of input reached!50 }51 return lookahead;52}53function parseExpression() {54 let expr;55 // debugger;56 if (lookahead.type == "STRING") {57 expr = {type: "value", value: lookahead.value};58 lex();59 return expr;60 } else if (lookahead.type == "NUMBER") {61 expr = {type: "value", value: lookahead.value};62 lex();63 return expr;64 } else if (lookahead.type == "WORD") {65 expr = {type: "word", name: lookahead.value};66 lex();67 return parseApply(expr);68 } else {69 throw new SyntaxError(`Unexpected syntax line ${lineno}: ${program.slice(0,10)}`);70 }71}72function parseApply(tree) {73 // if (!lookahead) return tree; // apply: /* vacio */74 // if (lookahead.type !== "LP") return tree; // apply: /* vacio */75 if (!lookahead) return tree; // End of input: apply: /* vacio */76 if ((lookahead.type === "RP")|| (lookahead.type === 'COMMA')) // apply: /* vacio */77 return tree;;78 if (lookahead.type !== "LP") throw new SyntaxError(`Error: Found ${lookahead.type}, Expected ',' or '(' or ')'`);79 lex();80 tree = {type: 'apply', operator: tree, args: []};81 while (lookahead && lookahead.type !== "RP") {82 let arg = parseExpression();83 tree.args.push(arg);84 if (lookahead && lookahead.type == "COMMA") {85 lex();86 } else if (!lookahead || lookahead.type !== "RP") {87 throw new SyntaxError(`Expected ',' or ')' at line ${lineno}: ... ${program.slice(0,20)}`);88 }89 }90 if (!lookahead) throw new SyntaxError(`Expected ')' at line ${lineno}: ... ${program.slice(0,20)}`);91 lex();92 return parseApply(tree);93}94function parse(p) {95 setProgram(p);96 // debugger;97 lex();98 let result = parseExpression();99 //console.log("result = ",inspect(result, {depth: null}));100 if (lookahead !== null) 101 throw new SyntaxError(`Unexpected input after reached the end of parsing ${lineno}: ${program.slice(0,10)}`);102 return result;103}104function parseFromFile(fileName) {105 try {106 let program = fs.readFileSync(fileName, 'utf8');107 let tree = parse(program);108 let json = JSON.stringify(tree, null, " ");109 fs.writeFileSync(fileName+".evm", json);110 }111 catch (err) {112 console.log(err);113 }114}115module.exports = {116 getProgram,117 lex,118 parse,119 parseApply,120 parseExpression,121 parseFromFile,122 setProgram,...

Full Screen

Full Screen

class_lookahead_a_n_n.js

Source:class_lookahead_a_n_n.js Github

copy

Full Screen

1var class_lookahead_a_n_n =2[3 [ "entry", "struct_lookahead_a_n_n_1_1entry.html", "struct_lookahead_a_n_n_1_1entry" ],4 [ "point", "struct_lookahead_a_n_n_1_1point.html", "struct_lookahead_a_n_n_1_1point" ],5 [ "entry", "class_lookahead_a_n_n.html#aa9f7a4ac2a0de9f715ed033989cddbd1", null ],6 [ "point", "class_lookahead_a_n_n.html#a05ec40384c098abfb52b1d27068b7130", null ],7 [ "LookaheadANN", "class_lookahead_a_n_n.html#a8dad9151982609ba7121492fbc9c1e8e", null ],8 [ "~LookaheadANN", "class_lookahead_a_n_n.html#a6a3ee4a4d05880f33b50f6bcf45fbba6", null ],9 [ "pre_cycle", "class_lookahead_a_n_n.html#aa5fb8cc158d38a690063e5f1dbf57b65", null ],10 [ "post_cycle", "class_lookahead_a_n_n.html#ae4aedd177125c86bab87b065ef436e7a", null ],11 [ "get_error", "class_lookahead_a_n_n.html#a803e93e772017cafe8eeea159a193335", null ],12 [ "record_packet", "class_lookahead_a_n_n.html#ad2411965565f6e8bcebf95ec8109152d", null ],13 [ "deque_clear", "class_lookahead_a_n_n.html#a093df32811a417287d3f701c4349b794", null ],14 [ "entry_prepare", "class_lookahead_a_n_n.html#a4c6934403b1ba9a94f00e677f8c3acfc", null ],15 [ "entry_train", "class_lookahead_a_n_n.html#af7f7ece48cd10cc164fec00be6427a0c", null ],16 [ "entry_valid", "class_lookahead_a_n_n.html#a2a4ce3ab5ab048de57b8d9176e220495", null ],17 [ "entry_predict", "class_lookahead_a_n_n.html#ad4e596d38b388769e1d095548d25c684", null ],18 [ "ann_filename", "class_lookahead_a_n_n.html#a5de3f10ef60a9de2325b5a10361c846f", null ],19 [ "ann_train", "class_lookahead_a_n_n.html#ad2cf76ca184ae4b5b88fda9e84dd6a65", null ],20 [ "set_pflog", "class_lookahead_a_n_n.html#a919a3e229c6a82e171d7b22e0fc2e439", null ],21 [ "inputfilter", "class_lookahead_a_n_n.html#a844ce45872feb8af9e29d1326cbebf68", null ],22 [ "outputfilter", "class_lookahead_a_n_n.html#ae7fb93c2f106a67f7fca15ef8020b72e", null ],23 [ "outputdefault", "class_lookahead_a_n_n.html#ac67d064cc8498ff32910706b9d2a85fa", null ],24 [ "npoint", "class_lookahead_a_n_n.html#aca783a09f05cc9e1079262793a5736cc", null ],25 [ "nfeature", "class_lookahead_a_n_n.html#a9ba68fb76e80ff47d9500ca6d2246c5e", null ],26 [ "nanninput", "class_lookahead_a_n_n.html#a5bb35b521d95b2d98c610a8e532a0cbb", null ],27 [ "nannoutput", "class_lookahead_a_n_n.html#aa17a34d16491815a6c329a775f479403", null ],28 [ "annlayers", "class_lookahead_a_n_n.html#a27dd9bffe99495d118ecb387d08e0252", null ],29 [ "annlayersz", "class_lookahead_a_n_n.html#a01e1d6f370630f7bd11b34bf7819c725", null ],30 [ "mintrainsetsz", "class_lookahead_a_n_n.html#a710a9588c9806260bbb338856f1f2a23", null ],31 [ "maxtrainepoch", "class_lookahead_a_n_n.html#a5539ce5f0b1c1e5c2134f09b68f7ce50", null ],32 [ "errmomentum", "class_lookahead_a_n_n.html#ade8a1256f77bee1c30e8db3946f98089", null ],33 [ "retrainerr", "class_lookahead_a_n_n.html#a692b2e86325f451cba626c0fcab55f26", null ],34 [ "validinterval", "class_lookahead_a_n_n.html#a5881ed37c4c71a19116bd711f22ce70c", null ],35 [ "ann", "class_lookahead_a_n_n.html#aa1bbed304661ce892c9f420e432d52c2", null ],36 [ "sendbuf", "class_lookahead_a_n_n.html#af6099f461af1d6db8d4a893fa84d789e", null ],37 [ "recvbuf", "class_lookahead_a_n_n.html#ab1ff847a9ecc1daa586da079e17fc02b", null ],38 [ "history", "class_lookahead_a_n_n.html#a8ef26f30815fe61994a279c2b2d39723", null ],39 [ "trainset", "class_lookahead_a_n_n.html#a733c8b9f451973041695efa166713821", null ],40 [ "predicterr", "class_lookahead_a_n_n.html#a7dbef37aa7d61c4dbf8404622dee2d47", null ],41 [ "lastpredict", "class_lookahead_a_n_n.html#a20fb27fb5203a273d0eb4eae1a1e0ef9", null ],42 [ "validcount", "class_lookahead_a_n_n.html#aa0ec0ec14ea3d8b2212198d90c8722a4", null ],43 [ "ve", "class_lookahead_a_n_n.html#a6865634bd149a174807cd272a31889b3", null ],44 [ "pflog", "class_lookahead_a_n_n.html#ab151ea3c0befc373f2ded05406e4ba48", null ]...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.click('input[name="q"]');7 await page.keyboard.type('Playwright');8 await page.keyboard.press('Enter');9 await page.waitForSelector('text=Playwright is a Node library to automate Chromium, Firefox and WebKit with a single API');10 await page.click('text=Playwright is a Node library to automate Chromium, Firefox and WebKit with a single API');11 await page.waitForSelector('text=Install Playwright');12 await page.click('text=Install Playwright');13 await page.waitForSelector('text=Playwright is a Node.js library to automate Chromium, Firefox and WebKit with a single API. It enables cross-browser web automation that is ever-green, capable, reliable and fast.');14 await browser.close();15})();16const { chromium } = require('playwright');17(async () => {18 const browser = await chromium.launch();19 const context = await browser.newContext();20 const page = await context.newPage();21 await page.click('input[name="q"]');22 await page.keyboard.type('Playwright');23 await page.keyboard.press('Enter');24 await page.waitForSelector('text=Playwright is a Node library to automate Chromium, Firefox and WebKit with a single API');25 await page.click('text=Playwright is a Node library to automate Chromium, Firefox and WebKit with a single API');26 await page.waitForSelector('text=Install Playwright');27 await page.click('text=Install Playwright');28 await page.waitForSelector('text=Playwright is a Node.js library to automate Chromium, Firefox and WebKit with a single API. It enables cross-browser web automation that is ever-green, capable, reliable and fast.');29 await browser.close();30})();31const { chromium } = require('playwright');32(async () => {33 const browser = await chromium.launch();34 const context = await browser.newContext();35 const page = await context.newPage();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.waitForSelector('text=I\'m Feeling Lucky');7 await page.click('text=I\'m Feeling Lucky');8 await page.waitForSelector('text=YouTube');9 await page.click('text=YouTube');10 await page.waitForSelector('text=Sign in');11 await page.click('text=Sign in');12 await page.waitForSelector('input[name="identifier"]');13 await page.fill('input[name="identifier"]', '

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.waitForSelector('text=Get Started');7 await page.click('text=Get Started');8 await page.waitForSelector('text=Playwright is a Node.js library to automate Chromium, Firefox and WebKit with a single API');9 await page.screenshot({ path: `example.png` });10 await browser.close();11})();12const { chromium } = require('playwright');13(async () => {14 const browser = await chromium.launch();15 const context = await browser.newContext();16 const page = await context.newPage();17 await page.waitForLoadState('networkidle');18 await page.click('text=Get Started');19 await page.waitForLoadState('networkidle');20 await page.screenshot({ path: `example.png` });21 await browser.close();22})();23const { chromium } = require('playwright');24(async () => {25 const browser = await chromium.launch();26 const context = await browser.newContext();27 const page = await context.newPage();28 await page.waitForSelector('text=Get Started');29 await page.click('text=Get Started');30 const [response] = await Promise.all([31 page.waitForResponse('**/docs/next/api/class-playwright*'),32 page.click('text=API reference'),33 ]);34 await page.screenshot({ path: `example.png` });35 await browser.close();36})();37const { chromium } = require('playwright');38(async () => {39 const browser = await chromium.launch();40 const context = await browser.newContext();41 const page = await context.newPage();42 const [request] = await Promise.all([43 page.waitForEvent('request'),

Full Screen

Using AI Code Generation

copy

Full Screen

1const {chromium} = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.waitForSelector('input[name="q"]');7 await page.fill('input[name="q"]', 'Playwright');8 await page.keyboard.press('Enter');9 await page.waitForSelector('text=Playwright');10 const [response] = await Promise.all([11 page.waitForResponse(response => response.url().includes('suggestqueries') && response.status() === 200),12 page.click('text=Playwright'),13 ]);14 console.log(response.url());15 await browser.close();16})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.route('**/*', route => {7 route.fulfill({8 });9 });10 await page.close();11 await context.close();12 await browser.close();13})();14const { chromium } = require('playwright');15(async () => {16 const browser = await chromium.launch();17 const context = await browser.newContext();18 const page = await context.newPage();19 page.on('request', request => {20 console.log(request.url());21 });22 await page.close();23 await context.close();24 await browser.close();25})();26const { chromium } = require('playwright');27(async () => {28 const browser = await chromium.launch();29 const context = await browser.newContext();30 const page = await context.newPage();31 page.on('response', response => {32 console.log(response.url());33 });34 await page.close();35 await context.close();36 await browser.close();37})();38const {chromium} = require('playwright')');39(async () => {40 const browser = await chromium.launch();41 const context = await browser.newContext();42 const page = await context.newPage();43 page.on('request', request => {44 console.log(request.url());45 });46 page.on('response', response => {47 console.log(response.url());48 });49 await page.close();50 await context.close();51 await browser.close();52})();53const { chromium } = require('playwright');54(async () => {

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright;2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.waitForSelector('input[name="q"]');7 await page.fill('input[name="q"]', 'Playwright');8 await page.keyboard.press('Enter');9 await page.waitForSelector('text=Playwright');10 const [response] = await Promise.all([11 page.waitForResponse(response => response.url().includes('suggestqueries') && response.status() === 200),12 page.click('text=Playwright'),13 ]);14 console.log(response.url());15 await browser.close();16})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright-internal');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.fill('input[aria-label="Search"]', 'hello world');7 await page.keyboard.press('Enter');8 await page.waitForNavigation();9 await page.screenshot({ path: 'example.png' });10 await browser.close();11})();12const { chromium } = require('playwright');13(async () => {14 const browser = await chromium.launch();15 const context = await browser.newContext();16 const page = await context.newPage();17 await page.fill('input[aria-label="Search"]', 'hello world');18 await page.keyboard.press('Enter');19 await page.waitForSelector('#search');20 await page.screenshot({ path: 'example.png' });21 await browser.close();22})();23equest() method of Playwright API24const { chromium } = require('playwright');25(async () => {

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = rire('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 await page.type('input[name="q"]', 'Hello World!');6 await page.click('input[type="submit"]');7 await pag.creensho{ path: `example.png` });8 await browser.close();9}();10const { chromium } = require('playwright');11(async () => { = await chromium.launch();12 const page = await browser.newPage();13 await page.type('input[name="q"]', 'Hello World!');14 await page.waitForSelector('input[type="submit"]');15 await page.click('input[type="submit"]');16 await page.screenshot({ path: `example.png` });17 await browser.close();18})();19const { chromium } = require('playwright');20(async () => {21 const browser = await chromium.launch();22 const page = await browser.newPage();23 await page.type('input[name="q"]', 'Hello World!');24 await page.waitForTimeout(1000);25 await page.click('input[type="submit"]');26 await page.screenshot({ path: `example.png` });27 await browser.close();28})();29const { chromium } = require('playwright');30(async () => {31 const browser = await chromium.launch();32 const page = await browser.newPage();33 await page.type('input[name="q"]', 'Hello World!');34 await page.waitForFunction('document.querySelector("input[type=submit]").disabled === false');35 await page.click('input[type="submit"]');36 await page.screenshot({ path: `example.png` });37 await browser.close();38})();39const { chromium } = require('playwright');40(async () => {41 const browser = await chromium.launch();42 const page = await browser.newPage();43 const browser = await chromium.launch();44 const context = await browser.newContext();45 const page = await context.newPage();46 await page.fill('input[aria-label="Search"]', 'hello world');47 await page.keyboard.press('Enter');48 await page.waitForFunction(() => document.querySelector('#search'));49 await page.screenshot({ path: 'example.png' });50 await browser.close();51})();52const { chromium } = require('playwright');53(async () => {54 const browser = await chromium.launch();55 const context = await browser.newContext();56 const page = await context.newPage();57 await page.fill('input[aria-label="Search"]', 'hello world');58 await page.keyboard.press('Enter');59 await page.screenshot({ path: 'example.png' });60 await browser.close();61})();62const { chromium } = require('playwright');63(async () => {

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 await page.type('input[name="q"]', 'Hello World!');6 await page.click('input[type="submit"]');7 await page.screenshot({ path: `example.png` });8 await browser.close();9})();10const { chromium } = require('playwright');11(async () => {12 const browser = await chromium.launch();13 const page = await browser.newPage();14 await page.type('input[name="q"]', 'Hello World!');15 await page.waitForSelector('input[type="submit"]');16 await page.click('input[type="submit"]');17 await page.screenshot({ path: `example.png` });18 await browser.close();19})();20const { chromium } = require('playwright');21(async () => {22 const browser = await chromium.launch();23 const page = await browser.newPage();24 await page.type('input[name="q"]', 'Hello World!');25 await page.waitForTimeout(1000);26 await page.click('input[type="submit"]');27 await page.screenshot({ path: `example.png` });28 await browser.close();29})();30const { chromium } = require('playwright');31(async () => {32 const browser = await chromium.launch();33 const page = await browser.newPage();34 await page.type('input[name="q"]', 'Hello World!');35 await page.waitForFunction('document.querySelector("input[type=submit]").disabled === false');36 await page.click('input[type="submit"]');37 await page.screenshot({ path: `example.png` });38 await browser.close();39})();40const { chromium } = require('playwright');41(async () => {42 const browser = await chromium.launch();43 const page = await browser.newPage();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { Page } = require('playwright/lib/server/page');2const { ElementHandle } = require('playwright/lib/server/dom');3const { helper } = require('playwright/lib/helper');4const { assert } = require('console');5Page.prototype.waitForSelector = async function(selector, options = {}) {6 const { timeout = this._timeoutSettings.timeout() } = options;7 const { state = 'visible' } = options;8 const handle = await this.$(selector, options);9 if (!handle) {10 throw new Error(`Unable to locate element: ${selector}`);11 }12 const isEnabled = await handle.evaluate(element => element.isEnabled());13 if (!isEnabled) {14 throw new Error(`Element: ${selector} is not enabled`);15 }16 const isClickable = await handle.evaluate(element => element.isClickable());17 if (!isClickable) {18 throw new Error(`Element: ${selector} is not clickable`);19 }20 await handle.waitForElementState(state, { timeout });21 return handle;22};23ElementHandle.prototype.waitForElementState = async function(state, options = {}) {24 const { timeout = this._timeoutSettings.timeout() } = options;25 const { polling = 'raf' } = options;26 const page = this._context._page;27 const mainFrame = page.mainFrame();28 const frame = this._context.frame;29 const mainExecutionContext = await mainFrame.executionContext();30 const handle = await this.evaluateHandle((element, state) => {31 const { waitForElementState } = require('playwright/lib/server/dom');32 return waitForElementState(element, state);33 }, state);34 const result = await mainExecutionContext._adoptBackendNodeId(await handle._evaluateHandle((node) => node._backendNodeId));35 await handle.dispose();36 return result;37};38helper.waitForEvent = async function(emitter, eventName, predicate, options = {}, timeout) {39 const { timeout: timeoutOverride = timeout } = options;40 let promise = new Promise((resolve, reject) => {41 const listener = (...args) => {42 if (predicate

Full Screen

Using AI Code Generation

copy

Full Screen

1const { Internal } = require('@playwright/test/lib/server/frames');2const { Page } = require('@playwright/test/lib/server/page');3const page = await context.newPage();4await page.waitForSelector('text=Login');5const internalFrame = await Internal.getInternalFrame(page);6const internalPage = await internalFrame._page;7const internalContext = await internalPage._context;8const internalBrowser = await internalContext._browser;9const internalServer = await internalBrowser._server;10const internalPlaywright = await internalServer._playwright;11const internalPlaywrightObject = await internalPlaywright._object;12const internalPlaywrightObject = await internalPlaywright._object;13const internalPlaywrightObject = await internalPlaywright._object;14const internalPlaywrightObject = await internalPlaywright._object;15const internalPlaywrightObject = await internalPlaywright._object;16const internalPlaywrightObject = await internalPlaywright._object;17const internalPlaywrightObject = await internalPlaywright._object;18const internalPlaywrightObject = await internalPlaywright._object;19const internalPlaywrightObject = await internalPlaywright._object;20const internalPlaywrightObject = await internalPlaywright._object;21const internalPlaywrightObject = await internalPlaywright._object;22const internalPlaywrightObject = await internalPlaywright._object;23const internalPlaywrightObject = await internalPlaywright._object;24const internalPlaywrightObject = await internalPlaywright._object;25const internalPlaywrightObject = await internalPlaywright._object;26const internalPlaywrightObject = await internalPlaywright._object;

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful