Commit 8e335a7c authored by JOE Thunyathep S's avatar JOE Thunyathep S
Browse files

up

parent 43ea69a2
Pipeline #1969 passed with stage
in 36 seconds
<!doctype html>
<title>CodeMirror: Fortran mode</title>
<meta charset="utf-8"/>
<link rel=stylesheet href="../../doc/docs.css">
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="fortran.js"></script>
<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
<div id=nav>
<a href="https://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png" alt=""></a>
<ul>
<li><a href="../../index.html">Home</a>
<li><a href="../../doc/manual.html">Manual</a>
<li><a href="https://github.com/codemirror/codemirror">Code</a>
</ul>
<ul>
<li><a href="../index.html">Language modes</a>
<li><a class=active href="#">Fortran</a>
</ul>
</div>
<article>
<h2>Fortran mode</h2>
<div><textarea id="code" name="code">
! Example Fortran code
program average
! Read in some numbers and take the average
! As written, if there are no data points, an average of zero is returned
! While this may not be desired behavior, it keeps this example simple
implicit none
real, dimension(:), allocatable :: points
integer :: number_of_points
real :: average_points=0., positive_average=0., negative_average=0.
write (*,*) "Input number of points to average:"
read (*,*) number_of_points
allocate (points(number_of_points))
write (*,*) "Enter the points to average:"
read (*,*) points
! Take the average by summing points and dividing by number_of_points
if (number_of_points > 0) average_points = sum(points) / number_of_points
! Now form average over positive and negative points only
if (count(points > 0.) > 0) then
positive_average = sum(points, points > 0.) / count(points > 0.)
end if
if (count(points < 0.) > 0) then
negative_average = sum(points, points < 0.) / count(points < 0.)
end if
deallocate (points)
! Print result to terminal
write (*,'(a,g12.4)') 'Average = ', average_points
write (*,'(a,g12.4)') 'Average of positive points = ', positive_average
write (*,'(a,g12.4)') 'Average of negative points = ', negative_average
end program average
</textarea></div>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
mode: "text/x-fortran"
});
</script>
<p><strong>MIME types defined:</strong> <code>text/x-fortran</code>.</p>
</article>
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("gas", function(_config, parserConfig) {
'use strict';
// If an architecture is specified, its initialization function may
// populate this array with custom parsing functions which will be
// tried in the event that the standard functions do not find a match.
var custom = [];
// The symbol used to start a line comment changes based on the target
// architecture.
// If no architecture is pased in "parserConfig" then only multiline
// comments will have syntax support.
var lineCommentStartSymbol = "";
// These directives are architecture independent.
// Machine specific directives should go in their respective
// architecture initialization function.
// Reference:
// http://sourceware.org/binutils/docs/as/Pseudo-Ops.html#Pseudo-Ops
var directives = {
".abort" : "builtin",
".align" : "builtin",
".altmacro" : "builtin",
".ascii" : "builtin",
".asciz" : "builtin",
".balign" : "builtin",
".balignw" : "builtin",
".balignl" : "builtin",
".bundle_align_mode" : "builtin",
".bundle_lock" : "builtin",
".bundle_unlock" : "builtin",
".byte" : "builtin",
".cfi_startproc" : "builtin",
".comm" : "builtin",
".data" : "builtin",
".def" : "builtin",
".desc" : "builtin",
".dim" : "builtin",
".double" : "builtin",
".eject" : "builtin",
".else" : "builtin",
".elseif" : "builtin",
".end" : "builtin",
".endef" : "builtin",
".endfunc" : "builtin",
".endif" : "builtin",
".equ" : "builtin",
".equiv" : "builtin",
".eqv" : "builtin",
".err" : "builtin",
".error" : "builtin",
".exitm" : "builtin",
".extern" : "builtin",
".fail" : "builtin",
".file" : "builtin",
".fill" : "builtin",
".float" : "builtin",
".func" : "builtin",
".global" : "builtin",
".gnu_attribute" : "builtin",
".hidden" : "builtin",
".hword" : "builtin",
".ident" : "builtin",
".if" : "builtin",
".incbin" : "builtin",
".include" : "builtin",
".int" : "builtin",
".internal" : "builtin",
".irp" : "builtin",
".irpc" : "builtin",
".lcomm" : "builtin",
".lflags" : "builtin",
".line" : "builtin",
".linkonce" : "builtin",
".list" : "builtin",
".ln" : "builtin",
".loc" : "builtin",
".loc_mark_labels" : "builtin",
".local" : "builtin",
".long" : "builtin",
".macro" : "builtin",
".mri" : "builtin",
".noaltmacro" : "builtin",
".nolist" : "builtin",
".octa" : "builtin",
".offset" : "builtin",
".org" : "builtin",
".p2align" : "builtin",
".popsection" : "builtin",
".previous" : "builtin",
".print" : "builtin",
".protected" : "builtin",
".psize" : "builtin",
".purgem" : "builtin",
".pushsection" : "builtin",
".quad" : "builtin",
".reloc" : "builtin",
".rept" : "builtin",
".sbttl" : "builtin",
".scl" : "builtin",
".section" : "builtin",
".set" : "builtin",
".short" : "builtin",
".single" : "builtin",
".size" : "builtin",
".skip" : "builtin",
".sleb128" : "builtin",
".space" : "builtin",
".stab" : "builtin",
".string" : "builtin",
".struct" : "builtin",
".subsection" : "builtin",
".symver" : "builtin",
".tag" : "builtin",
".text" : "builtin",
".title" : "builtin",
".type" : "builtin",
".uleb128" : "builtin",
".val" : "builtin",
".version" : "builtin",
".vtable_entry" : "builtin",
".vtable_inherit" : "builtin",
".warning" : "builtin",
".weak" : "builtin",
".weakref" : "builtin",
".word" : "builtin"
};
var registers = {};
function x86(_parserConfig) {
lineCommentStartSymbol = "#";
registers.ax = "variable";
registers.eax = "variable-2";
registers.rax = "variable-3";
registers.bx = "variable";
registers.ebx = "variable-2";
registers.rbx = "variable-3";
registers.cx = "variable";
registers.ecx = "variable-2";
registers.rcx = "variable-3";
registers.dx = "variable";
registers.edx = "variable-2";
registers.rdx = "variable-3";
registers.si = "variable";
registers.esi = "variable-2";
registers.rsi = "variable-3";
registers.di = "variable";
registers.edi = "variable-2";
registers.rdi = "variable-3";
registers.sp = "variable";
registers.esp = "variable-2";
registers.rsp = "variable-3";
registers.bp = "variable";
registers.ebp = "variable-2";
registers.rbp = "variable-3";
registers.ip = "variable";
registers.eip = "variable-2";
registers.rip = "variable-3";
registers.cs = "keyword";
registers.ds = "keyword";
registers.ss = "keyword";
registers.es = "keyword";
registers.fs = "keyword";
registers.gs = "keyword";
}
function armv6(_parserConfig) {
// Reference:
// http://infocenter.arm.com/help/topic/com.arm.doc.qrc0001l/QRC0001_UAL.pdf
// http://infocenter.arm.com/help/topic/com.arm.doc.ddi0301h/DDI0301H_arm1176jzfs_r0p7_trm.pdf
lineCommentStartSymbol = "@";
directives.syntax = "builtin";
registers.r0 = "variable";
registers.r1 = "variable";
registers.r2 = "variable";
registers.r3 = "variable";
registers.r4 = "variable";
registers.r5 = "variable";
registers.r6 = "variable";
registers.r7 = "variable";
registers.r8 = "variable";
registers.r9 = "variable";
registers.r10 = "variable";
registers.r11 = "variable";
registers.r12 = "variable";
registers.sp = "variable-2";
registers.lr = "variable-2";
registers.pc = "variable-2";
registers.r13 = registers.sp;
registers.r14 = registers.lr;
registers.r15 = registers.pc;
custom.push(function(ch, stream) {
if (ch === '#') {
stream.eatWhile(/\w/);
return "number";
}
});
}
var arch = (parserConfig.architecture || "x86").toLowerCase();
if (arch === "x86") {
x86(parserConfig);
} else if (arch === "arm" || arch === "armv6") {
armv6(parserConfig);
}
function nextUntilUnescaped(stream, end) {
var escaped = false, next;
while ((next = stream.next()) != null) {
if (next === end && !escaped) {
return false;
}
escaped = !escaped && next === "\\";
}
return escaped;
}
function clikeComment(stream, state) {
var maybeEnd = false, ch;
while ((ch = stream.next()) != null) {
if (ch === "/" && maybeEnd) {
state.tokenize = null;
break;
}
maybeEnd = (ch === "*");
}
return "comment";
}
return {
startState: function() {
return {
tokenize: null
};
},
token: function(stream, state) {
if (state.tokenize) {
return state.tokenize(stream, state);
}
if (stream.eatSpace()) {
return null;
}
var style, cur, ch = stream.next();
if (ch === "/") {
if (stream.eat("*")) {
state.tokenize = clikeComment;
return clikeComment(stream, state);
}
}
if (ch === lineCommentStartSymbol) {
stream.skipToEnd();
return "comment";
}
if (ch === '"') {
nextUntilUnescaped(stream, '"');
return "string";
}
if (ch === '.') {
stream.eatWhile(/\w/);
cur = stream.current().toLowerCase();
style = directives[cur];
return style || null;
}
if (ch === '=') {
stream.eatWhile(/\w/);
return "tag";
}
if (ch === '{') {
return "braket";
}
if (ch === '}') {
return "braket";
}
if (/\d/.test(ch)) {
if (ch === "0" && stream.eat("x")) {
stream.eatWhile(/[0-9a-fA-F]/);
return "number";
}
stream.eatWhile(/\d/);
return "number";
}
if (/\w/.test(ch)) {
stream.eatWhile(/\w/);
if (stream.eat(":")) {
return 'tag';
}
cur = stream.current().toLowerCase();
style = registers[cur];
return style || null;
}
for (var i = 0; i < custom.length; i++) {
style = custom[i](ch, stream, state);
if (style) {
return style;
}
}
},
lineComment: lineCommentStartSymbol,
blockCommentStart: "/*",
blockCommentEnd: "*/"
};
});
});
<!doctype html>
<title>CodeMirror: Gas mode</title>
<meta charset="utf-8"/>
<link rel=stylesheet href="../../doc/docs.css">
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="gas.js"></script>
<style>.CodeMirror {border: 2px inset #dee;}</style>
<div id=nav>
<a href="https://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png" alt=""></a>
<ul>
<li><a href="../../index.html">Home</a>
<li><a href="../../doc/manual.html">Manual</a>
<li><a href="https://github.com/codemirror/codemirror">Code</a>
</ul>
<ul>
<li><a href="../index.html">Language modes</a>
<li><a class=active href="#">Gas</a>
</ul>
</div>
<article>
<h2>Gas mode</h2>
<form>
<textarea id="code" name="code">
.syntax unified
.global main
/*
* A
* multi-line
* comment.
*/
@ A single line comment.
main:
push {sp, lr}
ldr r0, =message
bl puts
mov r0, #0
pop {sp, pc}
message:
.asciz "Hello world!<br />"
</textarea>
</form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
mode: {name: "gas", architecture: "ARMv6"},
});
</script>
<p>Handles AT&amp;T assembler syntax (more specifically this handles
the GNU Assembler (gas) syntax.)
It takes a single optional configuration parameter:
<code>architecture</code>, which can be one of <code>"ARM"</code>,
<code>"ARMv6"</code> or <code>"x86"</code>.
Including the parameter adds syntax for the registers and special
directives for the supplied architecture.
<p><strong>MIME types defined:</strong> <code>text/x-gas</code></p>
</article>
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"), require("../markdown/markdown"), require("../../addon/mode/overlay"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror", "../markdown/markdown", "../../addon/mode/overlay"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
var urlRE = /^((?:(?:aaas?|about|acap|adiumxtra|af[ps]|aim|apt|attachment|aw|beshare|bitcoin|bolo|callto|cap|chrome(?:-extension)?|cid|coap|com-eventbrite-attendee|content|crid|cvs|data|dav|dict|dlna-(?:playcontainer|playsingle)|dns|doi|dtn|dvb|ed2k|facetime|feed|file|finger|fish|ftp|geo|gg|git|gizmoproject|go|gopher|gtalk|h323|hcp|https?|iax|icap|icon|im|imap|info|ipn|ipp|irc[6s]?|iris(?:\.beep|\.lwz|\.xpc|\.xpcs)?|itms|jar|javascript|jms|keyparc|lastfm|ldaps?|magnet|mailto|maps|market|message|mid|mms|ms-help|msnim|msrps?|mtqp|mumble|mupdate|mvn|news|nfs|nih?|nntp|notes|oid|opaquelocktoken|palm|paparazzi|platform|pop|pres|proxy|psyc|query|res(?:ource)?|rmi|rsync|rtmp|rtsp|secondlife|service|session|sftp|sgn|shttp|sieve|sips?|skype|sm[bs]|snmp|soap\.beeps?|soldat|spotify|ssh|steam|svn|tag|teamspeak|tel(?:net)?|tftp|things|thismessage|tip|tn3270|tv|udp|unreal|urn|ut2004|vemmi|ventrilo|view-source|webcal|wss?|wtai|wyciwyg|xcon(?:-userid)?|xfire|xmlrpc\.beeps?|xmpp|xri|ymsgr|z39\.50[rs]?):(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]|\([^\s()<>]*\))+(?:\([^\s()<>]*\)|[^\s`*!()\[\]{};:'".,<>?«»“”‘’]))/i
CodeMirror.defineMode("gfm", function(config, modeConfig) {
var codeDepth = 0;
function blankLine(state) {
state.code = false;
return null;
}
var gfmOverlay = {
startState: function() {
return {
code: false,
codeBlock: false,
ateSpace: false
};
},
copyState: function(s) {
return {
code: s.code,
codeBlock: s.codeBlock,
ateSpace: s.ateSpace
};
},
token: function(stream, state) {
state.combineTokens = null;
// Hack to prevent formatting override inside code blocks (block and inline)
if (state.codeBlock) {
if (stream.match(/^```+/)) {
state.codeBlock = false;
return null;
}
stream.skipToEnd();
return null;
}
if (stream.sol()) {
state.code = false;
}
if (stream.sol() && stream.match(/^```+/)) {
stream.skipToEnd();
state.codeBlock = true;
return null;
}
// If this block is changed, it may need to be updated in Markdown mode
if (stream.peek() === '`') {
stream.next();
var before = stream.pos;
stream.eatWhile('`');
var difference = 1 + stream.pos - before;
if (!state.code) {
codeDepth = difference;
state.code = true;
} else {
if (difference === codeDepth) { // Must be exact
state.code = false;
}
}
return null;
} else if (state.code) {
stream.next();
return null;
}
// Check if space. If so, links can be formatted later on
if (stream.eatSpace()) {
state.ateSpace = true;
return null;
}
if (stream.sol() || state.ateSpace) {
state.ateSpace = false;
if (modeConfig.gitHubSpice !== false) {
if(stream.match(/^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+@)?(?=.{0,6}\d)(?:[a-f0-9]{7,40}\b)/)) {
// User/Project@SHA
// User@SHA
// SHA
state.combineTokens = true;
return "link";
} else if (stream.match(/^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+)?#[0-9]+\b/)) {
// User/Project#Num
// User#Num
// #Num
state.combineTokens = true;
return "link";
}
}
}
if (stream.match(urlRE) &&
stream.string.slice(stream.start - 2, stream.start) != "](" &&
(stream.start == 0 || /\W/.test(stream.string.charAt(stream.start - 1)))) {
// URLs
// Taken from http://daringfireball.net/2010/07/improved_regex_for_matching_urls
// And then (issue #1160) simplified to make it not crash the Chrome Regexp engine
// And then limited url schemes to the CommonMark list, so foo:bar isn't matched as a URL
state.combineTokens = true;
return "link";
}
stream.next();
return null;
},
blankLine: blankLine
};
var markdownConfig = {
taskLists: true,
strikethrough: true,
emoji: true
};
for (var attr in modeConfig) {
markdownConfig[attr] = modeConfig[attr];
}
markdownConfig.name = "markdown";
return CodeMirror.overlayMode(CodeMirror.getMode(config, markdownConfig), gfmOverlay);
}, "markdown");
CodeMirror.defineMIME("text/x-gfm", "gfm");
});
<!doctype html>
<title>CodeMirror: GFM mode</title>
<meta charset="utf-8"/>
<link rel=stylesheet href="../../doc/docs.css">
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="../../addon/mode/overlay.js"></script>
<script src="../xml/xml.js"></script>
<script src="../markdown/markdown.js"></script>
<script src="gfm.js"></script>
<script src="../javascript/javascript.js"></script>
<script src="../css/css.js"></script>
<script src="../htmlmixed/htmlmixed.js"></script>
<script src="../clike/clike.js"></script>
<script src="../meta.js"></script>
<style>
.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}
.cm-s-default .cm-emoji {color: #009688;}
</style>
<div id=nav>
<a href="https://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png" alt=""></a>
<ul>
<li><a href="../../index.html">Home</a>
<li><a href="../../doc/manual.html">Manual</a>
<li><a href="https://github.com/codemirror/codemirror">Code</a>
</ul>
<ul>
<li><a href="../index.html">Language modes</a>
<li><a class=active href="#">GFM</a>
</ul>
</div>
<article>
<h2>GFM mode</h2>
<form><textarea id="code" name="code">
GitHub Flavored Markdown
========================
Everything from markdown plus GFM features:
## URL autolinking
Underscores_are_allowed_between_words.
## Strikethrough text
GFM adds syntax to strikethrough text, which is missing from standard Markdown.
~~Mistaken text.~~
~~**works with other formatting**~~
~~spans across
lines~~
## Fenced code blocks (and syntax highlighting)
```javascript
for (var i = 0; i &lt; items.length; i++) {
console.log(items[i], i); // log them
}
```
## Task Lists
- [ ] Incomplete task list item
- [x] **Completed** task list item
## A bit of GitHub spice
See http://github.github.com/github-flavored-markdown/.
(Set `gitHubSpice: false` in mode options to disable):
* SHA: be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2
* User@SHA ref: mojombo@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2
* User/Project@SHA: mojombo/god@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2
* \#Num: #1
* User/#Num: mojombo#1
* User/Project#Num: mojombo/god#1
(Set `emoji: false` in mode options to disable):
* emoji: :smile:
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
mode: {
name: "gfm",
tokenTypeOverrides: {
emoji: "emoji"
}
},
lineNumbers: true,
theme: "default"
});
</script>
<p>Optionally depends on other modes for properly highlighted code blocks.</p>
<p>Gfm mode supports these options (apart those from base Markdown mode):</p>
<ul>
<li>
<d1>
<dt><code>gitHubSpice: boolean</code></dt>
<dd>Hashes, issues... (default: <code>true</code>).</dd>
</d1>
</li>
<li>
<d1>
<dt><code>taskLists: boolean</code></dt>
<dd><code>- [ ]</code> syntax (default: <code>true</code>).</dd>
</d1>
</li>
<li>
<d1>
<dt><code>strikethrough: boolean</code></dt>
<dd><code>~~foo~~</code> syntax (default: <code>true</code>).</dd>
</d1>
</li>
<li>
<d1>
<dt><code>emoji: boolean</code></dt>
<dd><code>:emoji:</code> syntax (default: <code>true</code>).</dd>
</d1>
</li>
</ul>
<p><strong>Parsing/Highlighting Tests:</strong> <a href="../../test/index.html#gfm_*">normal</a>, <a href="../../test/index.html#verbose,gfm_*">verbose</a>.</p>
</article>
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function() {
var config = {tabSize: 4, indentUnit: 2}
var mode = CodeMirror.getMode(config, "gfm");
function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }
var modeHighlightFormatting = CodeMirror.getMode(config, {name: "gfm", highlightFormatting: true});
function FT(name) { test.mode(name, modeHighlightFormatting, Array.prototype.slice.call(arguments, 1)); }
FT("codeBackticks",
"[comment&formatting&formatting-code `][comment foo][comment&formatting&formatting-code `]");
FT("doubleBackticks",
"[comment&formatting&formatting-code ``][comment foo ` bar][comment&formatting&formatting-code ``]");
FT("taskList",
"[variable-2&formatting&formatting-list&formatting-list-ul - ][meta&formatting&formatting-task [ ]]][variable-2 foo]",
"[variable-2&formatting&formatting-list&formatting-list-ul - ][property&formatting&formatting-task [x]]][variable-2 foo]");
FT("formatting_strikethrough",
"[strikethrough&formatting&formatting-strikethrough ~~][strikethrough foo][strikethrough&formatting&formatting-strikethrough ~~]");
FT("formatting_strikethrough",
"foo [strikethrough&formatting&formatting-strikethrough ~~][strikethrough bar][strikethrough&formatting&formatting-strikethrough ~~]");
FT("formatting_emoji",
"foo [builtin&formatting&formatting-emoji :smile:] foo");
MT("emInWordAsterisk",
"foo[em *bar*]hello");
MT("emInWordUnderscore",
"foo_bar_hello");
MT("emStrongUnderscore",
"[em&strong ___foo___] bar");
MT("taskListAsterisk",
"[variable-2 * ][link&variable-2 [[]]][variable-2 foo]", // Invalid; must have space or x between []
"[variable-2 * ][link&variable-2 [[ ]]][variable-2 bar]", // Invalid; must have space after ]
"[variable-2 * ][link&variable-2 [[x]]][variable-2 hello]", // Invalid; must have space after ]
"[variable-2 * ][meta [ ]]][variable-2 ][link&variable-2 [[world]]]", // Valid; tests reference style links
" [variable-3 * ][property [x]]][variable-3 foo]"); // Valid; can be nested
MT("taskListPlus",
"[variable-2 + ][link&variable-2 [[]]][variable-2 foo]", // Invalid; must have space or x between []
"[variable-2 + ][link&variable-2 [[x]]][variable-2 hello]", // Invalid; must have space after ]
"[variable-2 + ][meta [ ]]][variable-2 ][link&variable-2 [[world]]]", // Valid; tests reference style links
" [variable-3 + ][property [x]]][variable-3 foo]"); // Valid; can be nested
MT("taskListDash",
"[variable-2 - ][link&variable-2 [[]]][variable-2 foo]", // Invalid; must have space or x between []
"[variable-2 - ][link&variable-2 [[x]]][variable-2 hello]", // Invalid; must have space after ]
"[variable-2 - ][meta [ ]]][variable-2 world]", // Valid; tests reference style links
" [variable-3 - ][property [x]]][variable-3 foo]"); // Valid; can be nested
MT("taskListNumber",
"[variable-2 1. ][link&variable-2 [[]]][variable-2 foo]", // Invalid; must have space or x between []
"[variable-2 2. ][link&variable-2 [[ ]]][variable-2 bar]", // Invalid; must have space after ]
"[variable-2 3. ][meta [ ]]][variable-2 world]", // Valid; tests reference style links
" [variable-3 1. ][property [x]]][variable-3 foo]"); // Valid; can be nested
MT("SHA",
"foo [link be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2] bar");
MT("SHAEmphasis",
"[em *foo ][em&link be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2][em *]");
MT("shortSHA",
"foo [link be6a8cc] bar");
MT("tooShortSHA",
"foo be6a8c bar");
MT("longSHA",
"foo be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd22 bar");
MT("badSHA",
"foo be6a8cc1c1ecfe9489fb51e4869af15a13fc2cg2 bar");
MT("userSHA",
"foo [link bar@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2] hello");
MT("userSHAEmphasis",
"[em *foo ][em&link bar@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2][em *]");
MT("userProjectSHA",
"foo [link bar/hello@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2] world");
MT("userProjectSHAEmphasis",
"[em *foo ][em&link bar/hello@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2][em *]");
MT("wordSHA",
"ask for feedbac")
MT("num",
"foo [link #1] bar");
MT("numEmphasis",
"[em *foo ][em&link #1][em *]");
MT("badNum",
"foo #1bar hello");
MT("userNum",
"foo [link bar#1] hello");
MT("userNumEmphasis",
"[em *foo ][em&link bar#1][em *]");
MT("userProjectNum",
"foo [link bar/hello#1] world");
MT("userProjectNumEmphasis",
"[em *foo ][em&link bar/hello#1][em *]");
MT("vanillaLink",
"foo [link http://www.example.com/] bar");
MT("vanillaLinkNoScheme",
"foo [link www.example.com] bar");
MT("vanillaLinkHttps",
"foo [link https://www.example.com/] bar");
MT("vanillaLinkDataSchema",
"foo [link data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==] bar");
MT("vanillaLinkPunctuation",
"foo [link http://www.example.com/]. bar");
MT("vanillaLinkExtension",
"foo [link http://www.example.com/index.html] bar");
MT("vanillaLinkEmphasis",
"foo [em *][em&link http://www.example.com/index.html][em *] bar");
MT("notALink",
"foo asfd:asdf bar");
MT("notALink",
"[comment ``foo `bar` http://www.example.com/``] hello");
MT("notALink",
"[comment `foo]",
"[comment&link http://www.example.com/]",
"[comment `] foo",
"",
"[link http://www.example.com/]");
MT("strikethrough",
"[strikethrough ~~foo~~]");
MT("strikethroughWithStartingSpace",
"~~ foo~~");
MT("strikethroughUnclosedStrayTildes",
"[strikethrough ~~foo~~~]");
MT("strikethroughUnclosedStrayTildes",
"[strikethrough ~~foo ~~]");
MT("strikethroughUnclosedStrayTildes",
"[strikethrough ~~foo ~~ bar]");
MT("strikethroughUnclosedStrayTildes",
"[strikethrough ~~foo ~~ bar~~]hello");
MT("strikethroughOneLetter",
"[strikethrough ~~a~~]");
MT("strikethroughWrapped",
"[strikethrough ~~foo]",
"[strikethrough foo~~]");
MT("strikethroughParagraph",
"[strikethrough ~~foo]",
"",
"foo[strikethrough ~~bar]");
MT("strikethroughEm",
"[strikethrough ~~foo][em&strikethrough *bar*][strikethrough ~~]");
MT("strikethroughEm",
"[em *][em&strikethrough ~~foo~~][em *]");
MT("strikethroughStrong",
"[strikethrough ~~][strong&strikethrough **foo**][strikethrough ~~]");
MT("strikethroughStrong",
"[strong **][strong&strikethrough ~~foo~~][strong **]");
MT("emoji",
"text [builtin :blush:] text [builtin :v:] text [builtin :+1:] text",
":text text: [builtin :smiley_cat:]");
})();
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
/*
Gherkin mode - http://www.cukes.info/
Report bugs/issues here: https://github.com/codemirror/CodeMirror/issues
*/
// Following Objs from Brackets implementation: https://github.com/tregusti/brackets-gherkin/blob/master/main.js
//var Quotes = {
// SINGLE: 1,
// DOUBLE: 2
//};
//var regex = {
// keywords: /(Feature| {2}(Scenario|In order to|As|I)| {4}(Given|When|Then|And))/
//};
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("gherkin", function () {
return {
startState: function () {
return {
lineNumber: 0,
tableHeaderLine: false,
allowFeature: true,
allowBackground: false,
allowScenario: false,
allowSteps: false,
allowPlaceholders: false,
allowMultilineArgument: false,
inMultilineString: false,
inMultilineTable: false,
inKeywordLine: false
};
},
token: function (stream, state) {
if (stream.sol()) {
state.lineNumber++;
state.inKeywordLine = false;
if (state.inMultilineTable) {
state.tableHeaderLine = false;
if (!stream.match(/\s*\|/, false)) {
state.allowMultilineArgument = false;
state.inMultilineTable = false;
}
}
}
stream.eatSpace();
if (state.allowMultilineArgument) {
// STRING
if (state.inMultilineString) {
if (stream.match('"""')) {
state.inMultilineString = false;
state.allowMultilineArgument = false;
} else {
stream.match(/.*/);
}
return "string";
}
// TABLE
if (state.inMultilineTable) {
if (stream.match(/\|\s*/)) {
return "bracket";
} else {
stream.match(/[^\|]*/);
return state.tableHeaderLine ? "header" : "string";
}
}
// DETECT START
if (stream.match('"""')) {
// String
state.inMultilineString = true;
return "string";
} else if (stream.match("|")) {
// Table
state.inMultilineTable = true;
state.tableHeaderLine = true;
return "bracket";
}
}
// LINE COMMENT
if (stream.match(/#.*/)) {
return "comment";
// TAG
} else if (!state.inKeywordLine && stream.match(/@\S+/)) {
return "tag";
// FEATURE
} else if (!state.inKeywordLine && state.allowFeature && stream.match(/(機能|功能|フィーチャ|기능|โครงหลัก|ความสามารถ|ความต้องการทางธุรกิจ|ಹೆಚ್ಚಳ|గుణము|ਮੁਹਾਂਦਰਾ|ਨਕਸ਼ ਨੁਹਾਰ|ਖਾਸੀਅਤ|रूप लेख|وِیژگی|خاصية|תכונה|Функціонал|Функция|Функционалност|Функционал|Үзенчәлеклелек|Свойство|Особина|Мөмкинлек|Могућност|Λειτουργία|Δυνατότητα|Właściwość|Vlastnosť|Trajto|Tính năng|Savybė|Pretty much|Požiadavka|Požadavek|Potrzeba biznesowa|Özellik|Osobina|Ominaisuus|Omadus|OH HAI|Mogućnost|Mogucnost|Jellemző|Hwæt|Hwaet|Funzionalità|Funktionalitéit|Funktionalität|Funkcja|Funkcionalnost|Funkcionalitāte|Funkcia|Fungsi|Functionaliteit|Funcționalitate|Funcţionalitate|Functionalitate|Funcionalitat|Funcionalidade|Fonctionnalité|Fitur|Fīča|Feature|Eiginleiki|Egenskap|Egenskab|Característica|Caracteristica|Business Need|Aspekt|Arwedd|Ahoy matey!|Ability):/)) {
state.allowScenario = true;
state.allowBackground = true;
state.allowPlaceholders = false;
state.allowSteps = false;
state.allowMultilineArgument = false;
state.inKeywordLine = true;
return "keyword";
// BACKGROUND
} else if (!state.inKeywordLine && state.allowBackground && stream.match(/(背景|배경|แนวคิด|ಹಿನ್ನೆಲೆ|నేపథ్యం|ਪਿਛੋਕੜ|पृष्ठभूमि|زمینه|الخلفية|רקע|Тарих|Предыстория|Предистория|Позадина|Передумова|Основа|Контекст|Кереш|Υπόβαθρο|Założenia|Yo\-ho\-ho|Tausta|Taust|Situācija|Rerefons|Pozadina|Pozadie|Pozadí|Osnova|Latar Belakang|Kontext|Konteksts|Kontekstas|Kontekst|Háttér|Hannergrond|Grundlage|Geçmiş|Fundo|Fono|First off|Dis is what went down|Dasar|Contexto|Contexte|Context|Contesto|Cenário de Fundo|Cenario de Fundo|Cefndir|Bối cảnh|Bakgrunnur|Bakgrunn|Bakgrund|Baggrund|Background|B4|Antecedents|Antecedentes|Ær|Aer|Achtergrond):/)) {
state.allowPlaceholders = false;
state.allowSteps = true;
state.allowBackground = false;
state.allowMultilineArgument = false;
state.inKeywordLine = true;
return "keyword";
// SCENARIO OUTLINE
} else if (!state.inKeywordLine && state.allowScenario && stream.match(/(場景大綱|场景大纲|劇本大綱|剧本大纲|テンプレ|シナリオテンプレート|シナリオテンプレ|シナリオアウトライン|시나리오 개요|สรุปเหตุการณ์|โครงสร้างของเหตุการณ์|ವಿವರಣೆ|కథనం|ਪਟਕਥਾ ਰੂਪ ਰੇਖਾ|ਪਟਕਥਾ ਢਾਂਚਾ|परिदृश्य रूपरेखा|سيناريو مخطط|الگوی سناریو|תבנית תרחיש|Сценарийның төзелеше|Сценарий структураси|Структура сценарію|Структура сценария|Структура сценарија|Скица|Рамка на сценарий|Концепт|Περιγραφή Σεναρίου|Wharrimean is|Template Situai|Template Senario|Template Keadaan|Tapausaihio|Szenariogrundriss|Szablon scenariusza|Swa hwær swa|Swa hwaer swa|Struktura scenarija|Structură scenariu|Structura scenariu|Skica|Skenario konsep|Shiver me timbers|Senaryo taslağı|Schema dello scenario|Scenariomall|Scenariomal|Scenario Template|Scenario Outline|Scenario Amlinellol|Scenārijs pēc parauga|Scenarijaus šablonas|Reckon it's like|Raamstsenaarium|Plang vum Szenario|Plan du Scénario|Plan du scénario|Osnova scénáře|Osnova Scenára|Náčrt Scenáru|Náčrt Scénáře|Náčrt Scenára|MISHUN SRSLY|Menggariskan Senario|Lýsing Dæma|Lýsing Atburðarásar|Konturo de la scenaro|Koncept|Khung tình huống|Khung kịch bản|Forgatókönyv vázlat|Esquema do Cenário|Esquema do Cenario|Esquema del escenario|Esquema de l'escenari|Esbozo do escenario|Delineação do Cenário|Delineacao do Cenario|All y'all|Abstrakt Scenario|Abstract Scenario):/)) {
state.allowPlaceholders = true;
state.allowSteps = true;
state.allowMultilineArgument = false;
state.inKeywordLine = true;
return "keyword";
// EXAMPLES
} else if (state.allowScenario && stream.match(/(例子|例|サンプル|예|ชุดของเหตุการณ์|ชุดของตัวอย่าง|ಉದಾಹರಣೆಗಳು|ఉదాహరణలు|ਉਦਾਹਰਨਾਂ|उदाहरण|نمونه ها|امثلة|דוגמאות|Үрнәкләр|Сценарији|Примеры|Примери|Приклади|Мисоллар|Мисаллар|Σενάρια|Παραδείγματα|You'll wanna|Voorbeelden|Variantai|Tapaukset|Se þe|Se the|Se ðe|Scenarios|Scenariji|Scenarijai|Przykłady|Primjeri|Primeri|Příklady|Príklady|Piemēri|Példák|Pavyzdžiai|Paraugs|Örnekler|Juhtumid|Exemplos|Exemples|Exemple|Exempel|EXAMPLZ|Examples|Esempi|Enghreifftiau|Ekzemploj|Eksempler|Ejemplos|Dữ liệu|Dead men tell no tales|Dæmi|Contoh|Cenários|Cenarios|Beispiller|Beispiele|Atburðarásir):/)) {
state.allowPlaceholders = false;
state.allowSteps = true;
state.allowBackground = false;
state.allowMultilineArgument = true;
return "keyword";
// SCENARIO
} else if (!state.inKeywordLine && state.allowScenario && stream.match(/(場景|场景|劇本|剧本|シナリオ|시나리오|เหตุการณ์|ಕಥಾಸಾರಾಂಶ|సన్నివేశం|ਪਟਕਥਾ|परिदृश्य|سيناريو|سناریو|תרחיש|Сценарій|Сценарио|Сценарий|Пример|Σενάριο|Tình huống|The thing of it is|Tapaus|Szenario|Swa|Stsenaarium|Skenario|Situai|Senaryo|Senario|Scenaro|Scenariusz|Scenariu|Scénario|Scenario|Scenarijus|Scenārijs|Scenarij|Scenarie|Scénář|Scenár|Primer|MISHUN|Kịch bản|Keadaan|Heave to|Forgatókönyv|Escenario|Escenari|Cenário|Cenario|Awww, look mate|Atburðarás):/)) {
state.allowPlaceholders = false;
state.allowSteps = true;
state.allowBackground = false;
state.allowMultilineArgument = false;
state.inKeywordLine = true;
return "keyword";
// STEPS
} else if (!state.inKeywordLine && state.allowSteps && stream.match(/(那麼|那么|而且|當|当|并且|同時|同时|前提|假设|假設|假定|假如|但是|但し|並且|もし|ならば|ただし|しかし|かつ|하지만|조건|먼저|만일|만약|단|그리고|그러면|และ |เมื่อ |แต่ |ดังนั้น |กำหนดให้ |ಸ್ಥಿತಿಯನ್ನು |ಮತ್ತು |ನೀಡಿದ |ನಂತರ |ಆದರೆ |మరియు |చెప్పబడినది |కాని |ఈ పరిస్థితిలో |అప్పుడు |ਪਰ |ਤਦ |ਜੇਕਰ |ਜਿਵੇਂ ਕਿ |ਜਦੋਂ |ਅਤੇ |यदि |परन्तु |पर |तब |तदा |तथा |जब |चूंकि |किन्तु |कदा |और |अगर |و |هنگامی |متى |لكن |عندما |ثم |بفرض |با فرض |اما |اذاً |آنگاه |כאשר |וגם |בהינתן |אזי |אז |אבל |Якщо |Һәм |Унда |Тоді |Тогда |То |Также |Та |Пусть |Припустимо, що |Припустимо |Онда |Но |Нехай |Нәтиҗәдә |Лекин |Ләкин |Коли |Когда |Когато |Када |Кад |К тому же |І |И |Задато |Задати |Задате |Если |Допустим |Дано |Дадено |Вә |Ва |Бирок |Әмма |Әйтик |Әгәр |Аммо |Али |Але |Агар |А також |А |Τότε |Όταν |Και |Δεδομένου |Αλλά |Þurh |Þegar |Þa þe |Þá |Þa |Zatati |Zakładając |Zadato |Zadate |Zadano |Zadani |Zadan |Za předpokladu |Za predpokladu |Youse know when youse got |Youse know like when |Yna |Yeah nah |Y'know |Y |Wun |Wtedy |When y'all |When |Wenn |WEN |wann |Ve |Và |Und |Un |ugeholl |Too right |Thurh |Thì |Then y'all |Then |Tha the |Tha |Tetapi |Tapi |Tak |Tada |Tad |Stel |Soit |Siis |Și |Şi |Si |Sed |Se |Så |Quando |Quand |Quan |Pryd |Potom |Pokud |Pokiaľ |Però |Pero |Pak |Oraz |Onda |Ond |Oletetaan |Og |Och |O zaman |Niin |Nhưng |När |Når |Mutta |Men |Mas |Maka |Majd |Mając |Mais |Maar |mä |Ma |Lorsque |Lorsqu'|Logo |Let go and haul |Kun |Kuid |Kui |Kiedy |Khi |Ketika |Kemudian |Keď |Když |Kaj |Kai |Kada |Kad |Jeżeli |Jeśli |Ja |It's just unbelievable |Ir |I CAN HAZ |I |Ha |Givun |Givet |Given y'all |Given |Gitt |Gegeven |Gegeben seien |Gegeben sei |Gdy |Gangway! |Fakat |Étant donnés |Etant donnés |Étant données |Etant données |Étant donnée |Etant donnée |Étant donné |Etant donné |Et |És |Entonces |Entón |Então |Entao |En |Eğer ki |Ef |Eeldades |E |Ðurh |Duota |Dun |Donitaĵo |Donat |Donada |Do |Diyelim ki |Diberi |Dengan |Den youse gotta |DEN |De |Dato |Dați fiind |Daţi fiind |Dati fiind |Dati |Date fiind |Date |Data |Dat fiind |Dar |Dann |dann |Dan |Dados |Dado |Dadas |Dada |Ða ðe |Ða |Cuando |Cho |Cando |Când |Cand |Cal |But y'all |But at the end of the day I reckon |BUT |But |Buh |Blimey! |Biết |Bet |Bagi |Aye |awer |Avast! |Atunci |Atesa |Atès |Apabila |Anrhegedig a |Angenommen |And y'all |And |AN |An |an |Amikor |Amennyiben |Ama |Als |Alors |Allora |Ali |Aleshores |Ale |Akkor |Ak |Adott |Ac |Aber |A zároveň |A tiež |A taktiež |A také |A |a |7 |\* )/)) {
state.inStep = true;
state.allowPlaceholders = true;
state.allowMultilineArgument = true;
state.inKeywordLine = true;
return "keyword";
// INLINE STRING
} else if (stream.match(/"[^"]*"?/)) {
return "string";
// PLACEHOLDER
} else if (state.allowPlaceholders && stream.match(/<[^>]*>?/)) {
return "variable";
// Fall through
} else {
stream.next();
stream.eatWhile(/[^@"<#]/);
return null;
}
}
};
});
CodeMirror.defineMIME("text/x-feature", "gherkin");
});
<!doctype html>
<title>CodeMirror: Gherkin mode</title>
<meta charset="utf-8"/>
<link rel=stylesheet href="../../doc/docs.css">
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="gherkin.js"></script>
<style>.CodeMirror { border-top: 1px solid #ddd; border-bottom: 1px solid #ddd; }</style>
<div id=nav>
<a href="https://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png" alt=""></a>
<ul>
<li><a href="../../index.html">Home</a>
<li><a href="../../doc/manual.html">Manual</a>
<li><a href="https://github.com/codemirror/codemirror">Code</a>
</ul>
<ul>
<li><a href="../index.html">Language modes</a>
<li><a class=active href="#">Gherkin</a>
</ul>
</div>
<article>
<h2>Gherkin mode</h2>
<form><textarea id="code" name="code">
Feature: Using Google
Background:
Something something
Something else
Scenario: Has a homepage
When I navigate to the google home page
Then the home page should contain the menu and the search form
Scenario: Searching for a term
When I navigate to the google home page
When I search for Tofu
Then the search results page is displayed
Then the search results page contains 10 individual search results
Then the search results contain a link to the wikipedia tofu page
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
</script>
<p><strong>MIME types defined:</strong> <code>text/x-feature</code>.</p>
</article>
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("go", function(config) {
var indentUnit = config.indentUnit;
var keywords = {
"break":true, "case":true, "chan":true, "const":true, "continue":true,
"default":true, "defer":true, "else":true, "fallthrough":true, "for":true,
"func":true, "go":true, "goto":true, "if":true, "import":true,
"interface":true, "map":true, "package":true, "range":true, "return":true,
"select":true, "struct":true, "switch":true, "type":true, "var":true,
"bool":true, "byte":true, "complex64":true, "complex128":true,
"float32":true, "float64":true, "int8":true, "int16":true, "int32":true,
"int64":true, "string":true, "uint8":true, "uint16":true, "uint32":true,
"uint64":true, "int":true, "uint":true, "uintptr":true, "error": true,
"rune":true
};
var atoms = {
"true":true, "false":true, "iota":true, "nil":true, "append":true,
"cap":true, "close":true, "complex":true, "copy":true, "delete":true, "imag":true,
"len":true, "make":true, "new":true, "panic":true, "print":true,
"println":true, "real":true, "recover":true
};
var isOperatorChar = /[+\-*&^%:=<>!|\/]/;
var curPunc;
function tokenBase(stream, state) {
var ch = stream.next();
if (ch == '"' || ch == "'" || ch == "`") {
state.tokenize = tokenString(ch);
return state.tokenize(stream, state);
}
if (/[\d\.]/.test(ch)) {
if (ch == ".") {
stream.match(/^[0-9]+([eE][\-+]?[0-9]+)?/);
} else if (ch == "0") {
stream.match(/^[xX][0-9a-fA-F]+/) || stream.match(/^0[0-7]+/);
} else {
stream.match(/^[0-9]*\.?[0-9]*([eE][\-+]?[0-9]+)?/);
}
return "number";
}
if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
curPunc = ch;
return null;
}
if (ch == "/") {
if (stream.eat("*")) {
state.tokenize = tokenComment;
return tokenComment(stream, state);
}
if (stream.eat("/")) {
stream.skipToEnd();
return "comment";
}
}
if (isOperatorChar.test(ch)) {
stream.eatWhile(isOperatorChar);
return "operator";
}
stream.eatWhile(/[\w\$_\xa1-\uffff]/);
var cur = stream.current();
if (keywords.propertyIsEnumerable(cur)) {
if (cur == "case" || cur == "default") curPunc = "case";
return "keyword";
}
if (atoms.propertyIsEnumerable(cur)) return "atom";
return "variable";
}
function tokenString(quote) {
return function(stream, state) {
var escaped = false, next, end = false;
while ((next = stream.next()) != null) {
if (next == quote && !escaped) {end = true; break;}
escaped = !escaped && quote != "`" && next == "\\";
}
if (end || !(escaped || quote == "`"))
state.tokenize = tokenBase;
return "string";
};
}
function tokenComment(stream, state) {
var maybeEnd = false, ch;
while (ch = stream.next()) {
if (ch == "/" && maybeEnd) {
state.tokenize = tokenBase;
break;
}
maybeEnd = (ch == "*");
}
return "comment";
}
function Context(indented, column, type, align, prev) {
this.indented = indented;
this.column = column;
this.type = type;
this.align = align;
this.prev = prev;
}
function pushContext(state, col, type) {
return state.context = new Context(state.indented, col, type, null, state.context);
}
function popContext(state) {
if (!state.context.prev) return;
var t = state.context.type;
if (t == ")" || t == "]" || t == "}")
state.indented = state.context.indented;
return state.context = state.context.prev;
}
// Interface
return {
startState: function(basecolumn) {
return {
tokenize: null,
context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
indented: 0,
startOfLine: true
};
},
token: function(stream, state) {
var ctx = state.context;
if (stream.sol()) {
if (ctx.align == null) ctx.align = false;
state.indented = stream.indentation();
state.startOfLine = true;
if (ctx.type == "case") ctx.type = "}";
}
if (stream.eatSpace()) return null;
curPunc = null;
var style = (state.tokenize || tokenBase)(stream, state);
if (style == "comment") return style;
if (ctx.align == null) ctx.align = true;
if (curPunc == "{") pushContext(state, stream.column(), "}");
else if (curPunc == "[") pushContext(state, stream.column(), "]");
else if (curPunc == "(") pushContext(state, stream.column(), ")");
else if (curPunc == "case") ctx.type = "case";
else if (curPunc == "}" && ctx.type == "}") popContext(state);
else if (curPunc == ctx.type) popContext(state);
state.startOfLine = false;
return style;
},
indent: function(state, textAfter) {
if (state.tokenize != tokenBase && state.tokenize != null) return CodeMirror.Pass;
var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
if (ctx.type == "case" && /^(?:case|default)\b/.test(textAfter)) {
state.context.type = "}";
return ctx.indented;
}
var closing = firstChar == ctx.type;
if (ctx.align) return ctx.column + (closing ? 0 : 1);
else return ctx.indented + (closing ? 0 : indentUnit);
},
electricChars: "{}):",
closeBrackets: "()[]{}''\"\"``",
fold: "brace",
blockCommentStart: "/*",
blockCommentEnd: "*/",
lineComment: "//"
};
});
CodeMirror.defineMIME("text/x-go", "go");
});
<!doctype html>
<title>CodeMirror: Go mode</title>
<meta charset="utf-8"/>
<link rel=stylesheet href="../../doc/docs.css">
<link rel="stylesheet" href="../../lib/codemirror.css">
<link rel="stylesheet" href="../../theme/elegant.css">
<script src="../../lib/codemirror.js"></script>
<script src="../../addon/edit/matchbrackets.js"></script>
<script src="go.js"></script>
<style>.CodeMirror {border:1px solid #999; background:#ffc}</style>
<div id=nav>
<a href="https://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png" alt=""></a>
<ul>
<li><a href="../../index.html">Home</a>
<li><a href="../../doc/manual.html">Manual</a>
<li><a href="https://github.com/codemirror/codemirror">Code</a>
</ul>
<ul>
<li><a href="../index.html">Language modes</a>
<li><a class=active href="#">Go</a>
</ul>
</div>
<article>
<h2>Go mode</h2>
<form><textarea id="code" name="code">
// Prime Sieve in Go.
// Taken from the Go specification.
// Copyright © The Go Authors.
package main
import "fmt"
// Send the sequence 2, 3, 4, ... to channel 'ch'.
func generate(ch chan&lt;- int) {
for i := 2; ; i++ {
ch &lt;- i // Send 'i' to channel 'ch'
}
}
// Copy the values from channel 'src' to channel 'dst',
// removing those divisible by 'prime'.
func filter(src &lt;-chan int, dst chan&lt;- int, prime int) {
for i := range src { // Loop over values received from 'src'.
if i%prime != 0 {
dst &lt;- i // Send 'i' to channel 'dst'.
}
}
}
// The prime sieve: Daisy-chain filter processes together.
func sieve() {
ch := make(chan int) // Create a new channel.
go generate(ch) // Start generate() as a subprocess.
for {
prime := &lt;-ch
fmt.Print(prime, "\n")
ch1 := make(chan int)
go filter(ch, ch1, prime)
ch = ch1
}
}
func main() {
sieve()
}
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
theme: "elegant",
matchBrackets: true,
indentUnit: 8,
tabSize: 8,
indentWithTabs: true,
mode: "text/x-go"
});
</script>
<p><strong>MIME type:</strong> <code>text/x-go</code></p>
</article>
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("groovy", function(config) {
function words(str) {
var obj = {}, words = str.split(" ");
for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
return obj;
}
var keywords = words(
"abstract as assert boolean break byte case catch char class const continue def default " +
"do double else enum extends final finally float for goto if implements import in " +
"instanceof int interface long native new package private protected public return " +
"short static strictfp super switch synchronized threadsafe throw throws trait transient " +
"try void volatile while");
var blockKeywords = words("catch class def do else enum finally for if interface switch trait try while");
var standaloneKeywords = words("return break continue");
var atoms = words("null true false this");
var curPunc;
function tokenBase(stream, state) {
var ch = stream.next();
if (ch == '"' || ch == "'") {
return startString(ch, stream, state);
}
if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
curPunc = ch;
return null;
}
if (/\d/.test(ch)) {
stream.eatWhile(/[\w\.]/);
if (stream.eat(/eE/)) { stream.eat(/\+\-/); stream.eatWhile(/\d/); }
return "number";
}
if (ch == "/") {
if (stream.eat("*")) {
state.tokenize.push(tokenComment);
return tokenComment(stream, state);
}
if (stream.eat("/")) {
stream.skipToEnd();
return "comment";
}
if (expectExpression(state.lastToken, false)) {
return startString(ch, stream, state);
}
}
if (ch == "-" && stream.eat(">")) {
curPunc = "->";
return null;
}
if (/[+\-*&%=<>!?|\/~]/.test(ch)) {
stream.eatWhile(/[+\-*&%=<>|~]/);
return "operator";
}
stream.eatWhile(/[\w\$_]/);
if (ch == "@") { stream.eatWhile(/[\w\$_\.]/); return "meta"; }
if (state.lastToken == ".") return "property";
if (stream.eat(":")) { curPunc = "proplabel"; return "property"; }
var cur = stream.current();
if (atoms.propertyIsEnumerable(cur)) { return "atom"; }
if (keywords.propertyIsEnumerable(cur)) {
if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
else if (standaloneKeywords.propertyIsEnumerable(cur)) curPunc = "standalone";
return "keyword";
}
return "variable";
}
tokenBase.isBase = true;
function startString(quote, stream, state) {
var tripleQuoted = false;
if (quote != "/" && stream.eat(quote)) {
if (stream.eat(quote)) tripleQuoted = true;
else return "string";
}
function t(stream, state) {
var escaped = false, next, end = !tripleQuoted;
while ((next = stream.next()) != null) {
if (next == quote && !escaped) {
if (!tripleQuoted) { break; }
if (stream.match(quote + quote)) { end = true; break; }
}
if (quote == '"' && next == "$" && !escaped && stream.eat("{")) {
state.tokenize.push(tokenBaseUntilBrace());
return "string";
}
escaped = !escaped && next == "\\";
}
if (end) state.tokenize.pop();
return "string";
}
state.tokenize.push(t);
return t(stream, state);
}
function tokenBaseUntilBrace() {
var depth = 1;
function t(stream, state) {
if (stream.peek() == "}") {
depth--;
if (depth == 0) {
state.tokenize.pop();
return state.tokenize[state.tokenize.length-1](stream, state);
}
} else if (stream.peek() == "{") {
depth++;
}
return tokenBase(stream, state);
}
t.isBase = true;
return t;
}
function tokenComment(stream, state) {
var maybeEnd = false, ch;
while (ch = stream.next()) {
if (ch == "/" && maybeEnd) {
state.tokenize.pop();
break;
}
maybeEnd = (ch == "*");
}
return "comment";
}
function expectExpression(last, newline) {
return !last || last == "operator" || last == "->" || /[\.\[\{\(,;:]/.test(last) ||
last == "newstatement" || last == "keyword" || last == "proplabel" ||
(last == "standalone" && !newline);
}
function Context(indented, column, type, align, prev) {
this.indented = indented;
this.column = column;
this.type = type;
this.align = align;
this.prev = prev;
}
function pushContext(state, col, type) {
return state.context = new Context(state.indented, col, type, null, state.context);
}
function popContext(state) {
var t = state.context.type;
if (t == ")" || t == "]" || t == "}")
state.indented = state.context.indented;
return state.context = state.context.prev;
}
// Interface
return {
startState: function(basecolumn) {
return {
tokenize: [tokenBase],
context: new Context((basecolumn || 0) - config.indentUnit, 0, "top", false),
indented: 0,
startOfLine: true,
lastToken: null
};
},
token: function(stream, state) {
var ctx = state.context;
if (stream.sol()) {
if (ctx.align == null) ctx.align = false;
state.indented = stream.indentation();
state.startOfLine = true;
// Automatic semicolon insertion
if (ctx.type == "statement" && !expectExpression(state.lastToken, true)) {
popContext(state); ctx = state.context;
}
}
if (stream.eatSpace()) return null;
curPunc = null;
var style = state.tokenize[state.tokenize.length-1](stream, state);
if (style == "comment") return style;
if (ctx.align == null) ctx.align = true;
if ((curPunc == ";" || curPunc == ":") && ctx.type == "statement") popContext(state);
// Handle indentation for {x -> \n ... }
else if (curPunc == "->" && ctx.type == "statement" && ctx.prev.type == "}") {
popContext(state);
state.context.align = false;
}
else if (curPunc == "{") pushContext(state, stream.column(), "}");
else if (curPunc == "[") pushContext(state, stream.column(), "]");
else if (curPunc == "(") pushContext(state, stream.column(), ")");
else if (curPunc == "}") {
while (ctx.type == "statement") ctx = popContext(state);
if (ctx.type == "}") ctx = popContext(state);
while (ctx.type == "statement") ctx = popContext(state);
}
else if (curPunc == ctx.type) popContext(state);
else if (ctx.type == "}" || ctx.type == "top" || (ctx.type == "statement" && curPunc == "newstatement"))
pushContext(state, stream.column(), "statement");
state.startOfLine = false;
state.lastToken = curPunc || style;
return style;
},
indent: function(state, textAfter) {
if (!state.tokenize[state.tokenize.length-1].isBase) return CodeMirror.Pass;
var firstChar = textAfter && textAfter.charAt(0), ctx = state.context;
if (ctx.type == "statement" && !expectExpression(state.lastToken, true)) ctx = ctx.prev;
var closing = firstChar == ctx.type;
if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : config.indentUnit);
else if (ctx.align) return ctx.column + (closing ? 0 : 1);
else return ctx.indented + (closing ? 0 : config.indentUnit);
},
electricChars: "{}",
closeBrackets: {triples: "'\""},
fold: "brace",
blockCommentStart: "/*",
blockCommentEnd: "*/",
lineComment: "//"
};
});
CodeMirror.defineMIME("text/x-groovy", "groovy");
});
<!doctype html>
<title>CodeMirror: Groovy mode</title>
<meta charset="utf-8"/>
<link rel=stylesheet href="../../doc/docs.css">
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="../../addon/edit/matchbrackets.js"></script>
<script src="groovy.js"></script>
<style>.CodeMirror {border-top: 1px solid #500; border-bottom: 1px solid #500;}</style>
<div id=nav>
<a href="https://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png" alt=""></a>
<ul>
<li><a href="../../index.html">Home</a>
<li><a href="../../doc/manual.html">Manual</a>
<li><a href="https://github.com/codemirror/codemirror">Code</a>
</ul>
<ul>
<li><a href="../index.html">Language modes</a>
<li><a class=active href="#">Groovy</a>
</ul>
</div>
<article>
<h2>Groovy mode</h2>
<form><textarea id="code" name="code">
//Pattern for groovy script
def p = ~/.*\.groovy/
new File( 'd:\\scripts' ).eachFileMatch(p) {f ->
// imports list
def imports = []
f.eachLine {
// condition to detect an import instruction
ln -> if ( ln =~ '^import .*' ) {
imports << "${ln - 'import '}"
}
}
// print thmen
if ( ! imports.empty ) {
println f
imports.each{ println " $it" }
}
}
/* Coin changer demo code from http://groovy.codehaus.org */
enum UsCoin {
quarter(25), dime(10), nickel(5), penny(1)
UsCoin(v) { value = v }
final value
}
enum OzzieCoin {
fifty(50), twenty(20), ten(10), five(5)
OzzieCoin(v) { value = v }
final value
}
def plural(word, count) {
if (count == 1) return word
word[-1] == 'y' ? word[0..-2] + "ies" : word + "s"
}
def change(currency, amount) {
currency.values().inject([]){ list, coin ->
int count = amount / coin.value
amount = amount % coin.value
list += "$count ${plural(coin.toString(), count)}"
}
}
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
matchBrackets: true,
mode: "text/x-groovy"
});
</script>
<p><strong>MIME types defined:</strong> <code>text/x-groovy</code></p>
</article>
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"), require("../htmlmixed/htmlmixed"), require("../ruby/ruby"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror", "../htmlmixed/htmlmixed", "../ruby/ruby"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
// full haml mode. This handled embedded ruby and html fragments too
CodeMirror.defineMode("haml", function(config) {
var htmlMode = CodeMirror.getMode(config, {name: "htmlmixed"});
var rubyMode = CodeMirror.getMode(config, "ruby");
function rubyInQuote(endQuote) {
return function(stream, state) {
var ch = stream.peek();
if (ch == endQuote && state.rubyState.tokenize.length == 1) {
// step out of ruby context as it seems to complete processing all the braces
stream.next();
state.tokenize = html;
return "closeAttributeTag";
} else {
return ruby(stream, state);
}
};
}
function ruby(stream, state) {
if (stream.match("-#")) {
stream.skipToEnd();
return "comment";
}
return rubyMode.token(stream, state.rubyState);
}
function html(stream, state) {
var ch = stream.peek();
// handle haml declarations. All declarations that cant be handled here
// will be passed to html mode
if (state.previousToken.style == "comment" ) {
if (state.indented > state.previousToken.indented) {
stream.skipToEnd();
return "commentLine";
}
}
if (state.startOfLine) {
if (ch == "!" && stream.match("!!")) {
stream.skipToEnd();
return "tag";
} else if (stream.match(/^%[\w:#\.]+=/)) {
state.tokenize = ruby;
return "hamlTag";
} else if (stream.match(/^%[\w:]+/)) {
return "hamlTag";
} else if (ch == "/" ) {
stream.skipToEnd();
return "comment";
}
}
if (state.startOfLine || state.previousToken.style == "hamlTag") {
if ( ch == "#" || ch == ".") {
stream.match(/[\w-#\.]*/);
return "hamlAttribute";
}
}
// donot handle --> as valid ruby, make it HTML close comment instead
if (state.startOfLine && !stream.match("-->", false) && (ch == "=" || ch == "-" )) {
state.tokenize = ruby;
return state.tokenize(stream, state);
}
if (state.previousToken.style == "hamlTag" ||
state.previousToken.style == "closeAttributeTag" ||
state.previousToken.style == "hamlAttribute") {
if (ch == "(") {
state.tokenize = rubyInQuote(")");
return state.tokenize(stream, state);
} else if (ch == "{") {
if (!stream.match(/^\{%.*/)) {
state.tokenize = rubyInQuote("}");
return state.tokenize(stream, state);
}
}
}
return htmlMode.token(stream, state.htmlState);
}
return {
// default to html mode
startState: function() {
var htmlState = CodeMirror.startState(htmlMode);
var rubyState = CodeMirror.startState(rubyMode);
return {
htmlState: htmlState,
rubyState: rubyState,
indented: 0,
previousToken: { style: null, indented: 0},
tokenize: html
};
},
copyState: function(state) {
return {
htmlState : CodeMirror.copyState(htmlMode, state.htmlState),
rubyState: CodeMirror.copyState(rubyMode, state.rubyState),
indented: state.indented,
previousToken: state.previousToken,
tokenize: state.tokenize
};
},
token: function(stream, state) {
if (stream.sol()) {
state.indented = stream.indentation();
state.startOfLine = true;
}
if (stream.eatSpace()) return null;
var style = state.tokenize(stream, state);
state.startOfLine = false;
// dont record comment line as we only want to measure comment line with
// the opening comment block
if (style && style != "commentLine") {
state.previousToken = { style: style, indented: state.indented };
}
// if current state is ruby and the previous token is not `,` reset the
// tokenize to html
if (stream.eol() && state.tokenize == ruby) {
stream.backUp(1);
var ch = stream.peek();
stream.next();
if (ch && ch != ",") {
state.tokenize = html;
}
}
// reprocess some of the specific style tag when finish setting previousToken
if (style == "hamlTag") {
style = "tag";
} else if (style == "commentLine") {
style = "comment";
} else if (style == "hamlAttribute") {
style = "attribute";
} else if (style == "closeAttributeTag") {
style = null;
}
return style;
}
};
}, "htmlmixed", "ruby");
CodeMirror.defineMIME("text/x-haml", "haml");
});
<!doctype html>
<title>CodeMirror: HAML mode</title>
<meta charset="utf-8"/>
<link rel=stylesheet href="../../doc/docs.css">
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="../xml/xml.js"></script>
<script src="../htmlmixed/htmlmixed.js"></script>
<script src="../javascript/javascript.js"></script>
<script src="../ruby/ruby.js"></script>
<script src="haml.js"></script>
<style>.CodeMirror {background: #f8f8f8;}</style>
<div id=nav>
<a href="https://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png" alt=""></a>
<ul>
<li><a href="../../index.html">Home</a>
<li><a href="../../doc/manual.html">Manual</a>
<li><a href="https://github.com/codemirror/codemirror">Code</a>
</ul>
<ul>
<li><a href="../index.html">Language modes</a>
<li><a class=active href="#">HAML</a>
</ul>
</div>
<article>
<h2>HAML mode</h2>
<form><textarea id="code" name="code">
!!!
#content
.left.column(title="title"){:href => "/hello", :test => "#{hello}_#{world}"}
<!-- This is a comment -->
%h2 Welcome to our site!
%p= puts "HAML MODE"
.right.column
= render :partial => "sidebar"
.container
.row
.span8
%h1.title= @page_title
%p.title= @page_title
%p
/
The same as HTML comment
Hello multiline comment
-# haml comment
This wont be displayed
nor will this
Date/Time:
- now = DateTime.now
%strong= now
- if now > DateTime.parse("December 31, 2006")
= "Happy new " + "year!"
%title
= @title
\= @title
<h1>Title</h1>
<h1 title="HELLO">
Title
</h1>
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
mode: "text/x-haml"
});
</script>
<p><strong>MIME types defined:</strong> <code>text/x-haml</code>.</p>
<p><strong>Parsing/Highlighting Tests:</strong> <a href="../../test/index.html#haml_*">normal</a>, <a href="../../test/index.html#verbose,haml_*">verbose</a>.</p>
</article>
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function() {
var mode = CodeMirror.getMode({tabSize: 4, indentUnit: 2}, "haml");
function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }
// Requires at least one media query
MT("elementName",
"[tag %h1] Hey There");
MT("oneElementPerLine",
"[tag %h1] Hey There %h2");
MT("idSelector",
"[tag %h1][attribute #test] Hey There");
MT("classSelector",
"[tag %h1][attribute .hello] Hey There");
MT("docType",
"[tag !!! XML]");
MT("comment",
"[comment / Hello WORLD]");
MT("notComment",
"[tag %h1] This is not a / comment ");
MT("attributes",
"[tag %a]([variable title][operator =][string \"test\"]){[atom :title] [operator =>] [string \"test\"]}");
MT("htmlCode",
"[tag&bracket <][tag h1][tag&bracket >]Title[tag&bracket </][tag h1][tag&bracket >]");
MT("rubyBlock",
"[operator =][variable-2 @item]");
MT("selectorRubyBlock",
"[tag %a.selector=] [variable-2 @item]");
MT("nestedRubyBlock",
"[tag %a]",
" [operator =][variable puts] [string \"test\"]");
MT("multilinePlaintext",
"[tag %p]",
" Hello,",
" World");
MT("multilineRuby",
"[tag %p]",
" [comment -# this is a comment]",
" [comment and this is a comment too]",
" Date/Time",
" [operator -] [variable now] [operator =] [tag DateTime][operator .][property now]",
" [tag %strong=] [variable now]",
" [operator -] [keyword if] [variable now] [operator >] [tag DateTime][operator .][property parse]([string \"December 31, 2006\"])",
" [operator =][string \"Happy\"]",
" [operator =][string \"Belated\"]",
" [operator =][string \"Birthday\"]");
MT("multilineComment",
"[comment /]",
" [comment Multiline]",
" [comment Comment]");
MT("hamlComment",
"[comment -# this is a comment]");
MT("multilineHamlComment",
"[comment -# this is a comment]",
" [comment and this is a comment too]");
MT("multilineHTMLComment",
"[comment <!--]",
" [comment what a comment]",
" [comment -->]");
MT("hamlAfterRubyTag",
"[attribute .block]",
" [tag %strong=] [variable now]",
" [attribute .test]",
" [operator =][variable now]",
" [attribute .right]");
MT("stretchedRuby",
"[operator =] [variable puts] [string \"Hello\"],",
" [string \"World\"]");
MT("interpolationInHashAttribute",
//"[tag %div]{[atom :id] [operator =>] [string \"#{][variable test][string }_#{][variable ting][string }\"]} test");
"[tag %div]{[atom :id] [operator =>] [string \"#{][variable test][string }_#{][variable ting][string }\"]} test");
MT("interpolationInHTMLAttribute",
"[tag %div]([variable title][operator =][string \"#{][variable test][string }_#{][variable ting]()[string }\"]) Test");
})();
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"), require("../../addon/mode/simple"), require("../../addon/mode/multiplex"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror", "../../addon/mode/simple", "../../addon/mode/multiplex"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineSimpleMode("handlebars-tags", {
start: [
{ regex: /\{\{\{/, push: "handlebars_raw", token: "tag" },
{ regex: /\{\{!--/, push: "dash_comment", token: "comment" },
{ regex: /\{\{!/, push: "comment", token: "comment" },
{ regex: /\{\{/, push: "handlebars", token: "tag" }
],
handlebars_raw: [
{ regex: /\}\}\}/, pop: true, token: "tag" },
],
handlebars: [
{ regex: /\}\}/, pop: true, token: "tag" },
// Double and single quotes
{ regex: /"(?:[^\\"]|\\.)*"?/, token: "string" },
{ regex: /'(?:[^\\']|\\.)*'?/, token: "string" },
// Handlebars keywords
{ regex: />|[#\/]([A-Za-z_]\w*)/, token: "keyword" },
{ regex: /(?:else|this)\b/, token: "keyword" },
// Numeral
{ regex: /\d+/i, token: "number" },
// Atoms like = and .
{ regex: /=|~|@|true|false/, token: "atom" },
// Paths
{ regex: /(?:\.\.\/)*(?:[A-Za-z_][\w\.]*)+/, token: "variable-2" }
],
dash_comment: [
{ regex: /--\}\}/, pop: true, token: "comment" },
// Commented code
{ regex: /./, token: "comment"}
],
comment: [
{ regex: /\}\}/, pop: true, token: "comment" },
{ regex: /./, token: "comment" }
],
meta: {
blockCommentStart: "{{--",
blockCommentEnd: "--}}"
}
});
CodeMirror.defineMode("handlebars", function(config, parserConfig) {
var handlebars = CodeMirror.getMode(config, "handlebars-tags");
if (!parserConfig || !parserConfig.base) return handlebars;
return CodeMirror.multiplexingMode(
CodeMirror.getMode(config, parserConfig.base),
{open: "{{", close: /\}\}\}?/, mode: handlebars, parseDelimiters: true}
);
});
CodeMirror.defineMIME("text/x-handlebars-template", "handlebars");
});
<!doctype html>
<title>CodeMirror: Handlebars mode</title>
<meta charset="utf-8"/>
<link rel=stylesheet href="../../doc/docs.css">
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="../../addon/mode/simple.js"></script>
<script src="../../addon/mode/multiplex.js"></script>
<script src="../../addon/edit/matchbrackets.js"></script>
<script src="../xml/xml.js"></script>
<script src="handlebars.js"></script>
<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
<div id=nav>
<a href="https://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png" alt=""></a>
<ul>
<li><a href="../../index.html">Home</a>
<li><a href="../../doc/manual.html">Manual</a>
<li><a href="https://github.com/codemirror/codemirror">Code</a>
</ul>
<ul>
<li><a href="../index.html">Language modes</a>
<li><a class=active href="#">HTML mixed</a>
</ul>
</div>
<article>
<h2>Handlebars</h2>
<form><textarea id="code" name="code">
{{> breadcrumbs}}
{{!--
You can use the t function to get
content translated to the current locale, es:
{{t 'article_list'}}
--}}
<h1>{{t 'article_list'}}</h1>
{{! one line comment }}
{{{propertyContainingRawHtml}}}
{{#each articles}}
{{~title}}
<p>{{excerpt body size=120 ellipsis=true}}</p>
{{#with author}}
written by {{first_name}} {{last_name}}
from category: {{../category.title}}
{{#if @../last}}foobar!{{/if}}
{{/with~}}
{{#if promoted.latest}}Read this one! {{else}} This is ok! {{/if}}
{{#if @last}}<hr>{{/if}}
{{/each}}
{{#form new_comment}}
<input type="text" name="body">
{{/form}}
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
matchBrackets: true,
mode: {name: "handlebars", base: "text/html"}
});
</script>
<p>Handlebars syntax highlighting for CodeMirror.</p>
<p><strong>MIME types defined:</strong> <code>text/x-handlebars-template</code></p>
<p>Supported options: <code>base</code> to set the mode to
wrap. For example, use</p>
<pre>mode: {name: "handlebars", base: "text/html"}</pre>
<p>to highlight an HTML template.</p>
</article>
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function (mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"), require("../haskell/haskell"))
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror", "../haskell/haskell"], mod)
else // Plain browser env
mod(CodeMirror)
})(function (CodeMirror) {
"use strict"
CodeMirror.defineMode("haskell-literate", function (config, parserConfig) {
var baseMode = CodeMirror.getMode(config, (parserConfig && parserConfig.base) || "haskell")
return {
startState: function () {
return {
inCode: false,
baseState: CodeMirror.startState(baseMode)
}
},
token: function (stream, state) {
if (stream.sol()) {
if (state.inCode = stream.eat(">"))
return "meta"
}
if (state.inCode) {
return baseMode.token(stream, state.baseState)
} else {
stream.skipToEnd()
return "comment"
}
},
innerMode: function (state) {
return state.inCode ? {state: state.baseState, mode: baseMode} : null
}
}
}, "haskell")
CodeMirror.defineMIME("text/x-literate-haskell", "haskell-literate")
});
<!doctype html>
<title>CodeMirror: Haskell-literate mode</title>
<meta charset="utf-8"/>
<link rel=stylesheet href="../../doc/docs.css">
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="haskell-literate.js"></script>
<script src="../haskell/haskell.js"></script>
<style>.CodeMirror {
border-top : 1px solid #DDDDDD;
border-bottom : 1px solid #DDDDDD;
}</style>
<div id=nav>
<a href="https://codemirror.net"><h1>CodeMirror</h1><img id=logo
src="../../doc/logo.png"></a>
<ul>
<li><a href="../../index.html">Home</a>
<li><a href="../../doc/manual.html">Manual</a>
<li><a href="https://github.com/codemirror/codemirror">Code</a>
</ul>
<ul>
<li><a href="../index.html">Language modes</a>
<li><a class=active href="#">Haskell-literate</a>
</ul>
</div>
<article>
<h2>Haskell literate mode</h2>
<form>
<textarea id="code" name="code">
> {-# LANGUAGE OverloadedStrings #-}
> {-# OPTIONS_GHC -fno-warn-unused-do-bind #-}
> import Control.Applicative ((<$>), (<*>))
> import Data.Maybe (isJust)
> import Data.Text (Text)
> import Text.Blaze ((!))
> import qualified Data.Text as T
> import qualified Happstack.Server as Happstack
> import qualified Text.Blaze.Html5 as H
> import qualified Text.Blaze.Html5.Attributes as A
> import Text.Digestive
> import Text.Digestive.Blaze.Html5
> import Text.Digestive.Happstack
> import Text.Digestive.Util
Simple forms and validation
---------------------------
Let's start by creating a very simple datatype to represent a user:
> data User = User
> { userName :: Text
> , userMail :: Text
> } deriving (Show)
And dive in immediately to create a `Form` for a user. The `Form v m a` type
has three parameters:
- `v`: the type for messages and errors (usually a `String`-like type, `Text` in
this case);
- `m`: the monad we are operating in, not specified here;
- `a`: the return type of the `Form`, in this case, this is obviously `User`.
> userForm :: Monad m => Form Text m User
We create forms by using the `Applicative` interface. A few form types are
provided in the `Text.Digestive.Form` module, such as `text`, `string`,
`bool`...
In the `digestive-functors` library, the developer is required to label each
field using the `.:` operator. This might look like a bit of a burden, but it
allows you to do some really useful stuff, like separating the `Form` from the
actual HTML layout.
> userForm = User
> <$> "name" .: text Nothing
> <*> "mail" .: check "Not a valid email address" checkEmail (text Nothing)
The `check` function enables you to validate the result of a form. For example,
we can validate the email address with a really naive `checkEmail` function.
> checkEmail :: Text -> Bool
> checkEmail = isJust . T.find (== '@')
More validation
---------------
For our example, we also want descriptions of Haskell libraries, and in order to
do that, we need package versions...
> type Version = [Int]
We want to let the user input a version number such as `0.1.0.0`. This means we
need to validate if the input `Text` is of this form, and then we need to parse
it to a `Version` type. Fortunately, we can do this in a single function:
`validate` allows conversion between values, which can optionally fail.
`readMaybe :: Read a => String -> Maybe a` is a utility function imported from
`Text.Digestive.Util`.
> validateVersion :: Text -> Result Text Version
> validateVersion = maybe (Error "Cannot parse version") Success .
> mapM (readMaybe . T.unpack) . T.split (== '.')
A quick test in GHCi:
ghci> validateVersion (T.pack "0.3.2.1")
Success [0,3,2,1]
ghci> validateVersion (T.pack "0.oops")
Error "Cannot parse version"
It works! This means we can now easily add a `Package` type and a `Form` for it:
> data Category = Web | Text | Math
> deriving (Bounded, Enum, Eq, Show)
> data Package = Package Text Version Category
> deriving (Show)
> packageForm :: Monad m => Form Text m Package
> packageForm = Package
> <$> "name" .: text Nothing
> <*> "version" .: validate validateVersion (text (Just "0.0.0.1"))
> <*> "category" .: choice categories Nothing
> where
> categories = [(x, T.pack (show x)) | x <- [minBound .. maxBound]]
Composing forms
---------------
A release has an author and a package. Let's use this to illustrate the
composability of the digestive-functors library: we can reuse the forms we have
written earlier on.
> data Release = Release User Package
> deriving (Show)
> releaseForm :: Monad m => Form Text m Release
> releaseForm = Release
> <$> "author" .: userForm
> <*> "package" .: packageForm
Views
-----
As mentioned before, one of the advantages of using digestive-functors is
separation of forms and their actual HTML layout. In order to do this, we have
another type, `View`.
We can get a `View` from a `Form` by supplying input. A `View` contains more
information than a `Form`, it has:
- the original form;
- the input given by the user;
- any errors that have occurred.
It is this view that we convert to HTML. For this tutorial, we use the
[blaze-html] library, and some helpers from the `digestive-functors-blaze`
library.
[blaze-html]: http://jaspervdj.be/blaze/
Let's write a view for the `User` form. As you can see, we here refer to the
different fields in the `userForm`. The `errorList` will generate a list of
errors for the `"mail"` field.
> userView :: View H.Html -> H.Html
> userView view = do
> label "name" view "Name: "
> inputText "name" view
> H.br
>
> errorList "mail" view
> label "mail" view "Email address: "
> inputText "mail" view
> H.br
Like forms, views are also composable: let's illustrate that by adding a view
for the `releaseForm`, in which we reuse `userView`. In order to do this, we
take only the parts relevant to the author from the view by using `subView`. We
can then pass the resulting view to our own `userView`.
We have no special view code for `Package`, so we can just add that to
`releaseView` as well. `childErrorList` will generate a list of errors for each
child of the specified form. In this case, this means a list of errors from
`"package.name"` and `"package.version"`. Note how we use `foo.bar` to refer to
nested forms.
> releaseView :: View H.Html -> H.Html
> releaseView view = do
> H.h2 "Author"
> userView $ subView "author" view
>
> H.h2 "Package"
> childErrorList "package" view
>
> label "package.name" view "Name: "
> inputText "package.name" view
> H.br
>
> label "package.version" view "Version: "
> inputText "package.version" view
> H.br
>
> label "package.category" view "Category: "
> inputSelect "package.category" view
> H.br
The attentive reader might have wondered what the type parameter for `View` is:
it is the `String`-like type used for e.g. error messages.
But wait! We have
releaseForm :: Monad m => Form Text m Release
releaseView :: View H.Html -> H.Html
... doesn't this mean that we need a `View Text` rather than a `View Html`? The
answer is yes -- but having `View Html` allows us to write these views more
easily with the `digestive-functors-blaze` library. Fortunately, we will be able
to fix this using the `Functor` instance of `View`.
fmap :: Monad m => (v -> w) -> View v -> View w
A backend
---------
To finish this tutorial, we need to be able to actually run this code. We need
an HTTP server for that, and we use [Happstack] for this tutorial. The
`digestive-functors-happstack` library gives about everything we need for this.
[Happstack]: http://happstack.com/
> site :: Happstack.ServerPart Happstack.Response
> site = do
> Happstack.decodeBody $ Happstack.defaultBodyPolicy "/tmp" 4096 4096 4096
> r <- runForm "test" releaseForm
> case r of
> (view, Nothing) -> do
> let view' = fmap H.toHtml view
> Happstack.ok $ Happstack.toResponse $
> template $
> form view' "/" $ do
> releaseView view'
> H.br
> inputSubmit "Submit"
> (_, Just release) -> Happstack.ok $ Happstack.toResponse $
> template $ do
> css
> H.h1 "Release received"
> H.p $ H.toHtml $ show release
>
> main :: IO ()
> main = Happstack.simpleHTTP Happstack.nullConf site
Utilities
---------
> template :: H.Html -> H.Html
> template body = H.docTypeHtml $ do
> H.head $ do
> H.title "digestive-functors tutorial"
> css
> H.body body
> css :: H.Html
> css = H.style ! A.type_ "text/css" $ do
> "label {width: 130px; float: left; clear: both}"
> "ul.digestive-functors-error-list {"
> " color: red;"
> " list-style-type: none;"
> " padding-left: 0px;"
> "}"
</textarea>
</form>
<p><strong>MIME types
defined:</strong> <code>text/x-literate-haskell</code>.</p>
<p>Parser configuration parameters recognized: <code>base</code> to
set the base mode (defaults to <code>"haskell"</code>).</p>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {mode: "haskell-literate"});
</script>
</article>
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("haskell", function(_config, modeConfig) {
function switchState(source, setState, f) {
setState(f);
return f(source, setState);
}
// These should all be Unicode extended, as per the Haskell 2010 report
var smallRE = /[a-z_]/;
var largeRE = /[A-Z]/;
var digitRE = /\d/;
var hexitRE = /[0-9A-Fa-f]/;
var octitRE = /[0-7]/;
var idRE = /[a-z_A-Z0-9'\xa1-\uffff]/;
var symbolRE = /[-!#$%&*+.\/<=>?@\\^|~:]/;
var specialRE = /[(),;[\]`{}]/;
var whiteCharRE = /[ \t\v\f]/; // newlines are handled in tokenizer
function normal(source, setState) {
if (source.eatWhile(whiteCharRE)) {
return null;
}
var ch = source.next();
if (specialRE.test(ch)) {
if (ch == '{' && source.eat('-')) {
var t = "comment";
if (source.eat('#')) {
t = "meta";
}
return switchState(source, setState, ncomment(t, 1));
}
return null;
}
if (ch == '\'') {
if (source.eat('\\')) {
source.next(); // should handle other escapes here
}
else {
source.next();
}
if (source.eat('\'')) {
return "string";
}
return "string error";
}
if (ch == '"') {
return switchState(source, setState, stringLiteral);
}
if (largeRE.test(ch)) {
source.eatWhile(idRE);
if (source.eat('.')) {
return "qualifier";
}
return "variable-2";
}
if (smallRE.test(ch)) {
source.eatWhile(idRE);
return "variable";
}
if (digitRE.test(ch)) {
if (ch == '0') {
if (source.eat(/[xX]/)) {
source.eatWhile(hexitRE); // should require at least 1
return "integer";
}
if (source.eat(/[oO]/)) {
source.eatWhile(octitRE); // should require at least 1
return "number";
}
}
source.eatWhile(digitRE);
var t = "number";
if (source.match(/^\.\d+/)) {
t = "number";
}
if (source.eat(/[eE]/)) {
t = "number";
source.eat(/[-+]/);
source.eatWhile(digitRE); // should require at least 1
}
return t;
}
if (ch == "." && source.eat("."))
return "keyword";
if (symbolRE.test(ch)) {
if (ch == '-' && source.eat(/-/)) {
source.eatWhile(/-/);
if (!source.eat(symbolRE)) {
source.skipToEnd();
return "comment";
}
}
var t = "variable";
if (ch == ':') {
t = "variable-2";
}
source.eatWhile(symbolRE);
return t;
}
return "error";
}
function ncomment(type, nest) {
if (nest == 0) {
return normal;
}
return function(source, setState) {
var currNest = nest;
while (!source.eol()) {
var ch = source.next();
if (ch == '{' && source.eat('-')) {
++currNest;
}
else if (ch == '-' && source.eat('}')) {
--currNest;
if (currNest == 0) {
setState(normal);
return type;
}
}
}
setState(ncomment(type, currNest));
return type;
};
}
function stringLiteral(source, setState) {
while (!source.eol()) {
var ch = source.next();
if (ch == '"') {
setState(normal);
return "string";
}
if (ch == '\\') {
if (source.eol() || source.eat(whiteCharRE)) {
setState(stringGap);
return "string";
}
if (source.eat('&')) {
}
else {
source.next(); // should handle other escapes here
}
}
}
setState(normal);
return "string error";
}
function stringGap(source, setState) {
if (source.eat('\\')) {
return switchState(source, setState, stringLiteral);
}
source.next();
setState(normal);
return "error";
}
var wellKnownWords = (function() {
var wkw = {};
function setType(t) {
return function () {
for (var i = 0; i < arguments.length; i++)
wkw[arguments[i]] = t;
};
}
setType("keyword")(
"case", "class", "data", "default", "deriving", "do", "else", "foreign",
"if", "import", "in", "infix", "infixl", "infixr", "instance", "let",
"module", "newtype", "of", "then", "type", "where", "_");
setType("keyword")(
"\.\.", ":", "::", "=", "\\", "<-", "->", "@", "~", "=>");
setType("builtin")(
"!!", "$!", "$", "&&", "+", "++", "-", ".", "/", "/=", "<", "<*", "<=",
"<$>", "<*>", "=<<", "==", ">", ">=", ">>", ">>=", "^", "^^", "||", "*",
"*>", "**");
setType("builtin")(
"Applicative", "Bool", "Bounded", "Char", "Double", "EQ", "Either", "Enum",
"Eq", "False", "FilePath", "Float", "Floating", "Fractional", "Functor",
"GT", "IO", "IOError", "Int", "Integer", "Integral", "Just", "LT", "Left",
"Maybe", "Monad", "Nothing", "Num", "Ord", "Ordering", "Rational", "Read",
"ReadS", "Real", "RealFloat", "RealFrac", "Right", "Show", "ShowS",
"String", "True");
setType("builtin")(
"abs", "acos", "acosh", "all", "and", "any", "appendFile", "asTypeOf",
"asin", "asinh", "atan", "atan2", "atanh", "break", "catch", "ceiling",
"compare", "concat", "concatMap", "const", "cos", "cosh", "curry",
"cycle", "decodeFloat", "div", "divMod", "drop", "dropWhile", "either",
"elem", "encodeFloat", "enumFrom", "enumFromThen", "enumFromThenTo",
"enumFromTo", "error", "even", "exp", "exponent", "fail", "filter",
"flip", "floatDigits", "floatRadix", "floatRange", "floor", "fmap",
"foldl", "foldl1", "foldr", "foldr1", "fromEnum", "fromInteger",
"fromIntegral", "fromRational", "fst", "gcd", "getChar", "getContents",
"getLine", "head", "id", "init", "interact", "ioError", "isDenormalized",
"isIEEE", "isInfinite", "isNaN", "isNegativeZero", "iterate", "last",
"lcm", "length", "lex", "lines", "log", "logBase", "lookup", "map",
"mapM", "mapM_", "max", "maxBound", "maximum", "maybe", "min", "minBound",
"minimum", "mod", "negate", "not", "notElem", "null", "odd", "or",
"otherwise", "pi", "pred", "print", "product", "properFraction", "pure",
"putChar", "putStr", "putStrLn", "quot", "quotRem", "read", "readFile",
"readIO", "readList", "readLn", "readParen", "reads", "readsPrec",
"realToFrac", "recip", "rem", "repeat", "replicate", "return", "reverse",
"round", "scaleFloat", "scanl", "scanl1", "scanr", "scanr1", "seq",
"sequence", "sequence_", "show", "showChar", "showList", "showParen",
"showString", "shows", "showsPrec", "significand", "signum", "sin",
"sinh", "snd", "span", "splitAt", "sqrt", "subtract", "succ", "sum",
"tail", "take", "takeWhile", "tan", "tanh", "toEnum", "toInteger",
"toRational", "truncate", "uncurry", "undefined", "unlines", "until",
"unwords", "unzip", "unzip3", "userError", "words", "writeFile", "zip",
"zip3", "zipWith", "zipWith3");
var override = modeConfig.overrideKeywords;
if (override) for (var word in override) if (override.hasOwnProperty(word))
wkw[word] = override[word];
return wkw;
})();
return {
startState: function () { return { f: normal }; },
copyState: function (s) { return { f: s.f }; },
token: function(stream, state) {
var t = state.f(stream, function(s) { state.f = s; });
var w = stream.current();
return wellKnownWords.hasOwnProperty(w) ? wellKnownWords[w] : t;
},
blockCommentStart: "{-",
blockCommentEnd: "-}",
lineComment: "--"
};
});
CodeMirror.defineMIME("text/x-haskell", "haskell");
});
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment