Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kevinuga/5899153 to your computer and use it in GitHub Desktop.
Save kevinuga/5899153 to your computer and use it in GitHub Desktop.
Drupal 7 module for parse some sites to entities
This gist exceeds the recommended number of files (~10). To access all files, please clone this gist.
Changelog
---------
absoluteurl v1.6, March 12, 2010
---------------------------------
- added encode_url function to convert an absolute url to its percentage
encoded equivalent, according to RFC 3986
absoluteurl v1.5, March 11, 2010
---------------------------------
- fixed to allow spaces in the path of url
absoluteurl v1.4, October 2, 2009
----------------------------------------------
- Percentage encoding of the absolute url disabled.
absoluteurl v1.2, 2009-02-27
-----------------------------------------------
- Minor bug fix
absoluteurl v1.0, 2009-08-28
----------------------------------------
- Initial release
absoluteurl
---------------------
This script converts the relative url to absolute url, provided a base url.
For more, look here: http://publicmind.in/blog/urltoabsolute
Usage:
----------
Extract the script (url_to_absolute.php) into your web directory, include it into your current php file using:
require(path-to-file);
then, you can convert the relative url to absolute url by calling:
url_to_absolute( $baseUrl, $relativeUrl);
It return false on failure, otherwise returns the absolute url. If the $relativeUrl is a valid absolute url, it is returned without any modification.
Author/credits
-----------
1) Original author: David R. Nadeau, NadeauSoftware.com
2) Edited and maintained by: Nitin Kr, Gupta, publicmind.in
<?php
/**
* Edited by Nitin Kr. Gupta, publicmind.in
*/
/**
* Copyright (c) 2008, David R. Nadeau, NadeauSoftware.com.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* * Neither the names of David R. Nadeau or NadeauSoftware.com, nor
* the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
* WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*/
/*
* This is a BSD License approved by the Open Source Initiative (OSI).
* See: http://www.opensource.org/licenses/bsd-license.php
*/
/**
* Combine a base URL and a relative URL to produce a new
* absolute URL. The base URL is often the URL of a page,
* and the relative URL is a URL embedded on that page.
*
* This function implements the "absolutize" algorithm from
* the RFC3986 specification for URLs.
*
* This function supports multi-byte characters with the UTF-8 encoding,
* per the URL specification.
*
* Parameters:
* baseUrl the absolute base URL.
*
* url the relative URL to convert.
*
* Return values:
* An absolute URL that combines parts of the base and relative
* URLs, or FALSE if the base URL is not absolute or if either
* URL cannot be parsed.
*/
function url_to_absolute( $baseUrl, $relativeUrl )
{
// If relative URL has a scheme, clean path and return.
$r = split_url( $relativeUrl );
if ( $r === FALSE )
return FALSE;
if ( !empty( $r['scheme'] ) )
{
if ( !empty( $r['path'] ) && $r['path'][0] == '/' )
$r['path'] = url_remove_dot_segments( $r['path'] );
return join_url( $r );
}
// Make sure the base URL is absolute.
$b = split_url( $baseUrl );
if ( $b === FALSE || empty( $b['scheme'] ) || empty( $b['host'] ) )
return FALSE;
$r['scheme'] = $b['scheme'];
// If relative URL has an authority, clean path and return.
if ( isset( $r['host'] ) )
{
if ( !empty( $r['path'] ) )
$r['path'] = url_remove_dot_segments( $r['path'] );
return join_url( $r );
}
unset( $r['port'] );
unset( $r['user'] );
unset( $r['pass'] );
// Copy base authority.
$r['host'] = $b['host'];
if ( isset( $b['port'] ) ) $r['port'] = $b['port'];
if ( isset( $b['user'] ) ) $r['user'] = $b['user'];
if ( isset( $b['pass'] ) ) $r['pass'] = $b['pass'];
// If relative URL has no path, use base path
if ( empty( $r['path'] ) )
{
if ( !empty( $b['path'] ) )
$r['path'] = $b['path'];
if ( !isset( $r['query'] ) && isset( $b['query'] ) )
$r['query'] = $b['query'];
return join_url( $r );
}
// If relative URL path doesn't start with /, merge with base path
if ( $r['path'][0] != '/' )
{
$base = mb_strrchr( @$b['path'], '/', TRUE, 'UTF-8' );
if ( $base === FALSE ) $base = '';
$r['path'] = $base . '/' . $r['path'];
}
$r['path'] = url_remove_dot_segments( $r['path'] );
return join_url( $r );
}
/**
* Filter out "." and ".." segments from a URL's path and return
* the result.
*
* This function implements the "remove_dot_segments" algorithm from
* the RFC3986 specification for URLs.
*
* This function supports multi-byte characters with the UTF-8 encoding,
* per the URL specification.
*
* Parameters:
* path the path to filter
*
* Return values:
* The filtered path with "." and ".." removed.
*/
function url_remove_dot_segments( $path )
{
// multi-byte character explode
$inSegs = preg_split( '!/!u', $path );
$outSegs = array( );
foreach ( $inSegs as $seg )
{
if ( $seg == '' || $seg == '.')
continue;
if ( $seg == '..' )
array_pop( $outSegs );
else
array_push( $outSegs, $seg );
}
$outPath = implode( '/', $outSegs );
if ( $path[0] == '/' )
$outPath = '/' . $outPath;
// compare last multi-byte character against '/'
if ( $outPath != '/' &&
(mb_strlen($path)-1) == mb_strrpos( $path, '/', 'UTF-8' ) )
$outPath .= '/';
return $outPath;
}
/**
* This function parses an absolute or relative URL and splits it
* into individual components.
*
* RFC3986 specifies the components of a Uniform Resource Identifier (URI).
* A portion of the ABNFs are repeated here:
*
* URI-reference = URI
* / relative-ref
*
* URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
*
* relative-ref = relative-part [ "?" query ] [ "#" fragment ]
*
* hier-part = "//" authority path-abempty
* / path-absolute
* / path-rootless
* / path-empty
*
* relative-part = "//" authority path-abempty
* / path-absolute
* / path-noscheme
* / path-empty
*
* authority = [ userinfo "@" ] host [ ":" port ]
*
* So, a URL has the following major components:
*
* scheme
* The name of a method used to interpret the rest of
* the URL. Examples: "http", "https", "mailto", "file'.
*
* authority
* The name of the authority governing the URL's name
* space. Examples: "example.com", "user@example.com",
* "example.com:80", "user:password@example.com:80".
*
* The authority may include a host name, port number,
* user name, and password.
*
* The host may be a name, an IPv4 numeric address, or
* an IPv6 numeric address.
*
* path
* The hierarchical path to the URL's resource.
* Examples: "/index.htm", "/scripts/page.php".
*
* query
* The data for a query. Examples: "?search=google.com".
*
* fragment
* The name of a secondary resource relative to that named
* by the path. Examples: "#section1", "#header".
*
* An "absolute" URL must include a scheme and path. The authority, query,
* and fragment components are optional.
*
* A "relative" URL does not include a scheme and must include a path. The
* authority, query, and fragment components are optional.
*
* This function splits the $url argument into the following components
* and returns them in an associative array. Keys to that array include:
*
* "scheme" The scheme, such as "http".
* "host" The host name, IPv4, or IPv6 address.
* "port" The port number.
* "user" The user name.
* "pass" The user password.
* "path" The path, such as a file path for "http".
* "query" The query.
* "fragment" The fragment.
*
* One or more of these may not be present, depending upon the URL.
*
* Optionally, the "user", "pass", "host" (if a name, not an IP address),
* "path", "query", and "fragment" may have percent-encoded characters
* decoded. The "scheme" and "port" cannot include percent-encoded
* characters and are never decoded. Decoding occurs after the URL has
* been parsed.
*
* Parameters:
* url the URL to parse.
*
* decode an optional boolean flag selecting whether
* to decode percent encoding or not. Default = TRUE.
*
* Return values:
* the associative array of URL parts, or FALSE if the URL is
* too malformed to recognize any parts.
*/
function split_url( $url, $decode=FALSE)
{
// Character sets from RFC3986.
$xunressub = 'a-zA-Z\d\-._~\!$&\'()*+,;=';
$xpchar = $xunressub . ':@% ';
// Scheme from RFC3986.
$xscheme = '([a-zA-Z][a-zA-Z\d+-.]*)';
// User info (user + password) from RFC3986.
$xuserinfo = '(([' . $xunressub . '%]*)' .
'(:([' . $xunressub . ':%]*))?)';
// IPv4 from RFC3986 (without digit constraints).
$xipv4 = '(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})';
// IPv6 from RFC2732 (without digit and grouping constraints).
$xipv6 = '(\[([a-fA-F\d.:]+)\])';
// Host name from RFC1035. Technically, must start with a letter.
// Relax that restriction to better parse URL structure, then
// leave host name validation to application.
$xhost_name = '([a-zA-Z\d-.%]+)';
// Authority from RFC3986. Skip IP future.
$xhost = '(' . $xhost_name . '|' . $xipv4 . '|' . $xipv6 . ')';
$xport = '(\d*)';
$xauthority = '((' . $xuserinfo . '@)?' . $xhost .
'?(:' . $xport . ')?)';
// Path from RFC3986. Blend absolute & relative for efficiency.
$xslash_seg = '(/[' . $xpchar . ']*)';
$xpath_authabs = '((//' . $xauthority . ')((/[' . $xpchar . ']*)*))';
$xpath_rel = '([' . $xpchar . ']+' . $xslash_seg . '*)';
$xpath_abs = '(/(' . $xpath_rel . ')?)';
$xapath = '(' . $xpath_authabs . '|' . $xpath_abs .
'|' . $xpath_rel . ')';
// Query and fragment from RFC3986.
$xqueryfrag = '([' . $xpchar . '/?' . ']*)';
// URL.
$xurl = '^(' . $xscheme . ':)?' . $xapath . '?' .
'(\?' . $xqueryfrag . ')?(#' . $xqueryfrag . ')?$';
// Split the URL into components.
if ( !preg_match( '!' . $xurl . '!', $url, $m ) )
return FALSE;
if ( !empty($m[2]) ) $parts['scheme'] = strtolower($m[2]);
if ( !empty($m[7]) ) {
if ( isset( $m[9] ) ) $parts['user'] = $m[9];
else $parts['user'] = '';
}
if ( !empty($m[10]) ) $parts['pass'] = $m[11];
if ( !empty($m[13]) ) $h=$parts['host'] = $m[13];
else if ( !empty($m[14]) ) $parts['host'] = $m[14];
else if ( !empty($m[16]) ) $parts['host'] = $m[16];
else if ( !empty( $m[5] ) ) $parts['host'] = '';
if ( !empty($m[17]) ) $parts['port'] = $m[18];
if ( !empty($m[19]) ) $parts['path'] = $m[19];
else if ( !empty($m[21]) ) $parts['path'] = $m[21];
else if ( !empty($m[25]) ) $parts['path'] = $m[25];
if ( !empty($m[27]) ) $parts['query'] = $m[28];
if ( !empty($m[29]) ) $parts['fragment']= $m[30];
if ( !$decode )
return $parts;
if ( !empty($parts['user']) )
$parts['user'] = rawurldecode( $parts['user'] );
if ( !empty($parts['pass']) )
$parts['pass'] = rawurldecode( $parts['pass'] );
if ( !empty($parts['path']) )
$parts['path'] = rawurldecode( $parts['path'] );
if ( isset($h) )
$parts['host'] = rawurldecode( $parts['host'] );
if ( !empty($parts['query']) )
$parts['query'] = rawurldecode( $parts['query'] );
if ( !empty($parts['fragment']) )
$parts['fragment'] = rawurldecode( $parts['fragment'] );
return $parts;
}
/**
* This function joins together URL components to form a complete URL.
*
* RFC3986 specifies the components of a Uniform Resource Identifier (URI).
* This function implements the specification's "component recomposition"
* algorithm for combining URI components into a full URI string.
*
* The $parts argument is an associative array containing zero or
* more of the following:
*
* "scheme" The scheme, such as "http".
* "host" The host name, IPv4, or IPv6 address.
* "port" The port number.
* "user" The user name.
* "pass" The user password.
* "path" The path, such as a file path for "http".
* "query" The query.
* "fragment" The fragment.
*
* The "port", "user", and "pass" values are only used when a "host"
* is present.
*
* The optional $encode argument indicates if appropriate URL components
* should be percent-encoded as they are assembled into the URL. Encoding
* is only applied to the "user", "pass", "host" (if a host name, not an
* IP address), "path", "query", and "fragment" components. The "scheme"
* and "port" are never encoded. When a "scheme" and "host" are both
* present, the "path" is presumed to be hierarchical and encoding
* processes each segment of the hierarchy separately (i.e., the slashes
* are left alone).
*
* The assembled URL string is returned.
*
* Parameters:
* parts an associative array of strings containing the
* individual parts of a URL.
*
* encode an optional boolean flag selecting whether
* to do percent encoding or not. Default = true.
*
* Return values:
* Returns the assembled URL string. The string is an absolute
* URL if a scheme is supplied, and a relative URL if not. An
* empty string is returned if the $parts array does not contain
* any of the needed values.
*/
function join_url( $parts, $encode=FALSE)
{
if ( $encode )
{
if ( isset( $parts['user'] ) )
$parts['user'] = rawurlencode( $parts['user'] );
if ( isset( $parts['pass'] ) )
$parts['pass'] = rawurlencode( $parts['pass'] );
if ( isset( $parts['host'] ) &&
!preg_match( '!^(\[[\da-f.:]+\]])|([\da-f.:]+)$!ui', $parts['host'] ) )
$parts['host'] = rawurlencode( $parts['host'] );
if ( !empty( $parts['path'] ) )
$parts['path'] = preg_replace( '!%2F!ui', '/',
rawurlencode( $parts['path'] ) );
if ( isset( $parts['query'] ) )
$parts['query'] = rawurlencode( $parts['query'] );
if ( isset( $parts['fragment'] ) )
$parts['fragment'] = rawurlencode( $parts['fragment'] );
}
$url = '';
if ( !empty( $parts['scheme'] ) )
$url .= $parts['scheme'] . ':';
if ( isset( $parts['host'] ) )
{
$url .= '//';
if ( isset( $parts['user'] ) )
{
$url .= $parts['user'];
if ( isset( $parts['pass'] ) )
$url .= ':' . $parts['pass'];
$url .= '@';
}
if ( preg_match( '!^[\da-f]*:[\da-f.:]+$!ui', $parts['host'] ) )
$url .= '[' . $parts['host'] . ']'; // IPv6
else
$url .= $parts['host']; // IPv4 or name
if ( isset( $parts['port'] ) )
$url .= ':' . $parts['port'];
if ( !empty( $parts['path'] ) && $parts['path'][0] != '/' )
$url .= '/';
}
if ( !empty( $parts['path'] ) )
$url .= $parts['path'];
if ( isset( $parts['query'] ) )
$url .= '?' . $parts['query'];
if ( isset( $parts['fragment'] ) )
$url .= '#' . $parts['fragment'];
return $url;
}
/**
* This function encodes URL to form a URL which is properly
* percent encoded to replace disallowed characters.
*
* RFC3986 specifies the allowed characters in the URL as well as
* reserved characters in the URL. This function replaces all the
* disallowed characters in the URL with their repective percent
* encodings. Already encoded characters are not encoded again,
* such as '%20' is not encoded to '%2520'.
*
* Parameters:
* url the url to encode.
*
* Return values:
* Returns the encoded URL string.
*/
function encode_url($url) {
$reserved = array(
":" => '!%3A!ui',
"/" => '!%2F!ui',
"?" => '!%3F!ui',
"#" => '!%23!ui',
"[" => '!%5B!ui',
"]" => '!%5D!ui',
"@" => '!%40!ui',
"!" => '!%21!ui',
"$" => '!%24!ui',
"&" => '!%26!ui',
"'" => '!%27!ui',
"(" => '!%28!ui',
")" => '!%29!ui',
"*" => '!%2A!ui',
"+" => '!%2B!ui',
"," => '!%2C!ui',
";" => '!%3B!ui',
"=" => '!%3D!ui',
"%" => '!%25!ui',
);
$url = rawurlencode($url);
$url = preg_replace(array_values($reserved), array_keys($reserved), $url);
return $url;
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Active Line Demo</title>
<link rel="stylesheet" href="../lib/codemirror.css">
<script src="../lib/codemirror.js"></script>
<script src="../mode/xml/xml.js"></script>
<link rel="stylesheet" href="../doc/docs.css">
<style type="text/css">
.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}
.activeline {background: #e8f2ff !important;}
</style>
</head>
<body>
<h1>CodeMirror: Active Line Demo</h1>
<form><textarea id="code" name="code">
<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"
xmlns:georss="http://www.georss.org/georss"
xmlns:twitter="http://api.twitter.com">
<channel>
<title>Twitter / codemirror</title>
<link>http://twitter.com/codemirror</link>
<atom:link type="application/rss+xml"
href="http://twitter.com/statuses/user_timeline/242283288.rss" rel="self"/>
<description>Twitter updates from CodeMirror / codemirror.</description>
<language>en-us</language>
<ttl>40</ttl>
<item>
<title>codemirror: http://cloud-ide.com &#8212; they're springing up like mushrooms. This one
uses CodeMirror as its editor.</title>
<description>codemirror: http://cloud-ide.com &#8212; they're springing up like mushrooms. This
one uses CodeMirror as its editor.</description>
<pubDate>Thu, 17 Mar 2011 23:34:47 +0000</pubDate>
<guid>http://twitter.com/codemirror/statuses/48527733722058752</guid>
<link>http://twitter.com/codemirror/statuses/48527733722058752</link>
<twitter:source>web</twitter:source>
<twitter:place/>
</item>
<item>
<title>codemirror: Posted a description of the CodeMirror 2 internals at
http://codemirror.net/2/internals.html</title>
<description>codemirror: Posted a description of the CodeMirror 2 internals at
http://codemirror.net/2/internals.html</description>
<pubDate>Wed, 02 Mar 2011 12:15:09 +0000</pubDate>
<guid>http://twitter.com/codemirror/statuses/42920879788789760</guid>
<link>http://twitter.com/codemirror/statuses/42920879788789760</link>
<twitter:source>web</twitter:source>
<twitter:place/>
</item>
</channel>
</rss></textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
mode: "application/xml",
lineNumbers: true,
lineWrapping: true,
onCursorActivity: function() {
editor.setLineClass(hlLine, null, null);
hlLine = editor.setLineClass(editor.getCursor().line, null, "activeline");
}
});
var hlLine = editor.setLineClass(0, "activeline");
</script>
<p>Styling the current cursor line.</p>
</body>
</html>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Mode-Changing Demo</title>
<link rel="stylesheet" href="../lib/codemirror.css">
<script src="../lib/codemirror.js"></script>
<script src="../mode/javascript/javascript.js"></script>
<script src="../mode/scheme/scheme.js"></script>
<link rel="stylesheet" href="../doc/docs.css">
<style type="text/css">
.CodeMirror {border: 1px solid black;}
</style>
</head>
<body>
<h1>CodeMirror: Mode-Changing demo</h1>
<form><textarea id="code" name="code">
;; If there is Scheme code in here, the editor will be in Scheme mode.
;; If you put in JS instead, it'll switch to JS mode.
(define (double x)
(* x x))
</textarea></form>
<p>On changes to the content of the above editor, a (crude) script
tries to auto-detect the language used, and switches the editor to
either JavaScript or Scheme mode based on that.</p>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
mode: "scheme",
lineNumbers: true,
matchBrackets: true,
tabMode: "indent",
onChange: function() {
clearTimeout(pending);
setTimeout(update, 400);
}
});
var pending;
function looksLikeScheme(code) {
return !/^\s*\(\s*function\b/.test(code) && /^\s*[;\(]/.test(code);
}
function update() {
editor.setOption("mode", looksLikeScheme(editor.getValue()) ? "scheme" : "javascript");
}
</script>
</body>
</html>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Close-Tag Demo</title>
<link rel="stylesheet" href="../lib/codemirror.css">
<script src="../lib/codemirror.js"></script>
<script src="../lib/util/closetag.js"></script>
<script src="../mode/xml/xml.js"></script>
<script src="../mode/javascript/javascript.js"></script>
<script src="../mode/css/css.js"></script>
<script src="../mode/htmlmixed/htmlmixed.js"></script>
<link rel="stylesheet" href="../doc/docs.css">
<style type="text/css">
.CodeMirror {border-top: 1px solid #eee; border-bottom: 1px solid #eee;}
</style>
</head>
<body>
<h1>Close-Tag Demo</h1>
<ul>
<li>Type an html tag. When you type '>' or '/', the tag will auto-close/complete. Block-level tags will indent.</li>
<li>There are options for disabling tag closing or customizing the list of tags to indent.</li>
<li>Works with "text/html" (based on htmlmixed.js or xml.js) mode.</li>
<li>View source for key binding details.</li>
</p>
<form><textarea id="code" name="code"></textarea></form>
<script type="text/javascript">
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
mode: 'text/html',
//closeTagEnabled: false, // Set this option to disable tag closing behavior without having to remove the key bindings.
//closeTagIndent: false, // Pass false or an array of tag names to override the default indentation behavior.
extraKeys: {
"'>'": function(cm) { cm.closeTag(cm, '>'); },
"'/'": function(cm) { cm.closeTag(cm, '/'); }
},
/*
// extraKeys is the easier way to go, but if you need native key event processing, this should work too.
onKeyEvent: function(cm, e) {
if (e.type == 'keydown') {
var c = e.keyCode || e.which;
if (c == 190 || c == 191) {
try {
cm.closeTag(cm, c == 190 ? '>' : '/');
e.stop();
return true;
} catch (e) {
if (e != CodeMirror.Pass) throw e;
}
}
}
return false;
},
*/
wordWrap: true
});
</script>
</body>
</html>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Autocomplete Demo</title>
<link rel="stylesheet" href="../lib/codemirror.css">
<script src="../lib/codemirror.js"></script>
<script src="../lib/util/simple-hint.js"></script>
<link rel="stylesheet" href="../lib/util/simple-hint.css">
<script src="../lib/util/javascript-hint.js"></script>
<script src="../mode/javascript/javascript.js"></script>
<link rel="stylesheet" href="../doc/docs.css">
<style type="text/css">.CodeMirror {border: 1px solid #eee;} .CodeMirror-scroll { height: 100% }</style>
</head>
<body>
<h1>CodeMirror: Autocomplete demo</h1>
<form><textarea id="code" name="code">
function getCompletions(token, context) {
var found = [], start = token.string;
function maybeAdd(str) {
if (str.indexOf(start) == 0) found.push(str);
}
function gatherCompletions(obj) {
if (typeof obj == "string") forEach(stringProps, maybeAdd);
else if (obj instanceof Array) forEach(arrayProps, maybeAdd);
else if (obj instanceof Function) forEach(funcProps, maybeAdd);
for (var name in obj) maybeAdd(name);
}
if (context) {
// If this is a property, see if it belongs to some object we can
// find in the current environment.
var obj = context.pop(), base;
if (obj.className == "js-variable")
base = window[obj.string];
else if (obj.className == "js-string")
base = "";
else if (obj.className == "js-atom")
base = 1;
while (base != null && context.length)
base = base[context.pop().string];
if (base != null) gatherCompletions(base);
}
else {
// If not, just look in the window object and any local scope
// (reading into JS mode internals to get at the local variables)
for (var v = token.state.localVars; v; v = v.next) maybeAdd(v.name);
gatherCompletions(window);
forEach(keywords, maybeAdd);
}
return found;
}
</textarea></form>
<p>Press <strong>ctrl-space</strong> to activate autocompletion. See
the code (<a href="../lib/util/simple-hint.js">here</a>
and <a href="../lib/util/javascript-hint.js">here</a>) to figure out
how it works.</p>
<script>
CodeMirror.commands.autocomplete = function(cm) {
CodeMirror.simpleHint(cm, CodeMirror.javascriptHint);
}
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
extraKeys: {"Ctrl-Space": "autocomplete"}
});
</script>
</body>
</html>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Emacs bindings demo</title>
<link rel="stylesheet" href="../lib/codemirror.css">
<script src="../lib/codemirror.js"></script>
<script src="../mode/clike/clike.js"></script>
<script src="../keymap/emacs.js"></script>
<link rel="stylesheet" href="../doc/docs.css">
<style type="text/css">
.CodeMirror {border-top: 1px solid #eee; border-bottom: 1px solid #eee;}
</style>
</head>
<body>
<h1>CodeMirror: Emacs bindings demo</h1>
<form><textarea id="code" name="code">
#include "syscalls.h"
/* getchar: simple buffered version */
int getchar(void)
{
static char buf[BUFSIZ];
static char *bufp = buf;
static int n = 0;
if (n == 0) { /* buffer is empty */
n = read(0, buf, sizeof buf);
bufp = buf;
}
return (--n >= 0) ? (unsigned char) *bufp++ : EOF;
}
</textarea></form>
<p>The emacs keybindings are enabled by
including <a href="../keymap/emacs.js">keymap/emacs.js</a> and setting
the <code>keyMap</code> option to <code>"emacs"</code>. Because
CodeMirror's internal API is quite different from Emacs, they are only
a loose approximation of actual emacs bindings, though.</p>
<p>Also note that a lot of browsers disallow certain keys from being
captured. For example, Chrome blocks both Ctrl-W and Ctrl-N, with the
result that idiomatic use of Emacs keys will constantly close your tab
or open a new window.</p>
<script>
CodeMirror.commands.save = function() {
var elt = editor.getWrapperElement();
elt.style.background = "#def";
setTimeout(function() { elt.style.background = ""; }, 300);
};
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
mode: "text/x-csrc",
keyMap: "emacs"
});
</script>
</body>
</html>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Code Folding Demo</title>
<link rel="stylesheet" href="../lib/codemirror.css">
<script src="../lib/codemirror.js"></script>
<script src="../lib/util/foldcode.js"></script>
<script src="../mode/javascript/javascript.js"></script>
<script src="../mode/xml/xml.js"></script>
<link rel="stylesheet" href="../doc/docs.css">
<style type="text/css">
.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}
.CodeMirror-gutter {min-width: 2.6em; cursor: pointer;}
</style>
</head>
<body>
<h1>CodeMirror: Code Folding Demo</h1>
<p>Demonstration of code folding using the code
in <a href="../lib/util/foldcode.js"><code>foldcode.js</code></a>.
Press ctrl-q or click on the gutter to fold a block, again
to unfold.</p>
<form>
<div style="max-width: 50em; margin-bottom: 1em">JavaScript:<br><textarea id="code" name="code"></textarea></div>
<div style="max-width: 50em">HTML:<br><textarea id="code-html" name="code-html"></textarea></div>
</form>
<script id="script">
window.onload = function() {
var te = document.getElementById("code");
var sc = document.getElementById("script");
te.value = (sc.textContent || sc.innerText || sc.innerHTML).replace(/^\s*/, "");
sc.innerHTML = "";
var te_html = document.getElementById("code-html");
te_html.value = "<html>\n " + document.documentElement.innerHTML + "\n</html>";
var foldFunc = CodeMirror.newFoldFunction(CodeMirror.braceRangeFinder);
window.editor = CodeMirror.fromTextArea(te, {
mode: "javascript",
lineNumbers: true,
lineWrapping: true,
onGutterClick: foldFunc,
extraKeys: {"Ctrl-Q": function(cm){foldFunc(cm, cm.getCursor().line);}}
});
foldFunc(editor, 9);
foldFunc(editor, 20);
var foldFunc_html = CodeMirror.newFoldFunction(CodeMirror.tagRangeFinder);
window.editor_html = CodeMirror.fromTextArea(te_html, {
mode: "text/html",
lineNumbers: true,
lineWrapping: true,
onGutterClick: foldFunc_html,
extraKeys: {"Ctrl-Q": function(cm){foldFunc_html(cm, cm.getCursor().line);}}
})
foldFunc_html(editor_html, 1);
foldFunc_html(editor_html, 15);
};
</script>
</body>
</html>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Formatting Demo</title>
<link rel="stylesheet" href="../lib/codemirror.css">
<script src="../lib/codemirror.js"></script>
<script src="../lib/util/formatting.js"></script>
<script src="../mode/css/css.js"></script>
<script src="../mode/xml/xml.js"></script>
<script src="../mode/javascript/javascript.js"></script>
<script src="../mode/htmlmixed/htmlmixed.js"></script>
<link rel="stylesheet" href="../doc/docs.css">
<style type="text/css">
.CodeMirror {
border: 1px solid #eee;
}
td {
padding-right: 20px;
}
</style>
</head>
<body>
<h1>CodeMirror: Formatting demo</h1>
<form><textarea id="code" name="code"><script> function (s,e){ for(var i=0; i < 1; i++) test("test();a=1");} </script>
<script>
function test(c){ for (var i = 0; i < 10; i++){ process("a.b();c = null;", 300);}
}
</script>
<table><tr><td>test 1</td></tr><tr><td>test 2</td></tr></table>
<script> function test() { return 1;} </script>
<style> .test { font-size: medium; font-family: monospace; }
</style></textarea></form>
<p>Select a piece of code and click one of the links below to apply automatic formatting to the selected text or comment/uncomment the selected text. Note that the formatting behavior depends on the current block's mode.
<table>
<tr>
<td>
<a href="javascript:autoFormatSelection()">
Autoformat Selected
</a>
</td>
<td>
<a href="javascript:commentSelection(true)">
Comment Selected
</a>
</td>
<td>
<a href="javascript:commentSelection(false)">
Uncomment Selected
</a>
</td>
</tr>
</table>
</p>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
mode: "htmlmixed"
});
CodeMirror.commands["selectAll"](editor);
function getSelectedRange() {
return { from: editor.getCursor(true), to: editor.getCursor(false) };
}
function autoFormatSelection() {
var range = getSelectedRange();
editor.autoFormatRange(range.from, range.to);
}
function commentSelection(isComment) {
var range = getSelectedRange();
editor.commentRange(isComment, range.from, range.to);
}
</script>
</body>
</html>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Full Screen Editing</title>
<link rel="stylesheet" href="../lib/codemirror.css">
<script src="../lib/codemirror.js"></script>
<link rel="stylesheet" href="../theme/night.css">
<script src="../mode/xml/xml.js"></script>
<link rel="stylesheet" href="../doc/docs.css">
<style type="text/css">
.CodeMirror-fullscreen {
display: block;
position: absolute;
top: 0; left: 0;
width: 100%;
z-index: 9999;
}
</style>
</head>
<body>
<h1>CodeMirror: Full Screen Editing</h1>
<form><textarea id="code" name="code" rows="5">
<dt id="option_indentWithTabs"><code>indentWithTabs (boolean)</code></dt>
<dd>Whether, when indenting, the first N*8 spaces should be
replaced by N tabs. Default is false.</dd>
<dt id="option_tabMode"><code>tabMode (string)</code></dt>
<dd>Determines what happens when the user presses the tab key.
Must be one of the following:
<dl>
<dt><code>"classic" (the default)</code></dt>
<dd>When nothing is selected, insert a tab. Otherwise,
behave like the <code>"shift"</code> mode. (When shift is
held, this behaves like the <code>"indent"</code> mode.)</dd>
<dt><code>"shift"</code></dt>
<dd>Indent all selected lines by
one <a href="#option_indentUnit"><code>indentUnit</code></a>.
If shift was held while pressing tab, un-indent all selected
lines one unit.</dd>
<dt><code>"indent"</code></dt>
<dd>Indent the line the 'correctly', based on its syntactic
context. Only works if the
mode <a href="#indent">supports</a> it.</dd>
<dt><code>"default"</code></dt>
<dd>Do not capture tab presses, let the browser apply its
default behaviour (which usually means it skips to the next
control).</dd>
</dl></dd>
<dt id="option_enterMode"><code>enterMode (string)</code></dt>
<dd>Determines whether and how new lines are indented when the
enter key is pressed. The following modes are supported:
<dl>
<dt><code>"indent" (the default)</code></dt>
<dd>Use the mode's indentation rules to give the new line
the correct indentation.</dd>
<dt><code>"keep"</code></dt>
<dd>Indent the line the same as the previous line.</dd>
<dt><code>"flat"</code></dt>
<dd>Do not indent the new line.</dd>
</dl></dd>
<dt id="option_enterMode"><code>enterMode (string)</code></dt>
<dd>Determines whether and how new lines are indented when the
enter key is pressed. The following modes are supported:
<dl>
<dt><code>"indent" (the default)</code></dt>
<dd>Use the mode's indentation rules to give the new line
the correct indentation.</dd>
<dt><code>"keep"</code></dt>
<dd>Indent the line the same as the previous line.</dd>
<dt><code>"flat"</code></dt>
<dd>Do not indent the new line.</dd>
</dl></dd>
<dt id="option_enterMode"><code>enterMode (string)</code></dt>
<dd>Determines whether and how new lines are indented when the
enter key is pressed. The following modes are supported:
<dl>
<dt><code>"indent" (the default)</code></dt>
<dd>Use the mode's indentation rules to give the new line
the correct indentation.</dd>
<dt><code>"keep"</code></dt>
<dd>Indent the line the same as the previous line.</dd>
<dt><code>"flat"</code></dt>
<dd>Do not indent the new line.</dd>
</dl></dd>
<dt id="option_enterMode"><code>enterMode (string)</code></dt>
<dd>Determines whether and how new lines are indented when the
enter key is pressed. The following modes are supported:
<dl>
<dt><code>"indent" (the default)</code></dt>
<dd>Use the mode's indentation rules to give the new line
the correct indentation.</dd>
<dt><code>"keep"</code></dt>
<dd>Indent the line the same as the previous line.</dd>
<dt><code>"flat"</code></dt>
<dd>Do not indent the new line.</dd>
</dl></dd>
</textarea></form>
<script>
function isFullScreen(cm) {
return /\bCodeMirror-fullscreen\b/.test(cm.getWrapperElement().className);
}
function winHeight() {
return window.innerHeight || (document.documentElement || document.body).clientHeight;
}
function setFullScreen(cm, full) {
var wrap = cm.getWrapperElement(), scroll = cm.getScrollerElement();
if (full) {
wrap.className += " CodeMirror-fullscreen";
scroll.style.height = winHeight() + "px";
document.documentElement.style.overflow = "hidden";
} else {
wrap.className = wrap.className.replace(" CodeMirror-fullscreen", "");
scroll.style.height = "";
document.documentElement.style.overflow = "";
}
cm.refresh();
}
CodeMirror.connect(window, "resize", function() {
var showing = document.body.getElementsByClassName("CodeMirror-fullscreen")[0];
if (!showing) return;
showing.CodeMirror.getScrollerElement().style.height = winHeight() + "px";
});
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
theme: "night",
extraKeys: {
"F11": function(cm) {
setFullScreen(cm, !isFullScreen(cm));
},
"Esc": function(cm) {
if (isFullScreen(cm)) setFullScreen(cm, false);
}
}
});
</script>
<p>Press <strong>F11</strong> when cursor is in the editor to toggle full screen editing. <strong>Esc</strong> can also be used to <i>exit</i> full screen editing.</p>
</body>
</html>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Lazy Mode Loading Demo</title>
<link rel="stylesheet" href="../lib/codemirror.css">
<script src="../lib/codemirror.js"></script>
<script src="../lib/util/loadmode.js"></script>
<link rel="stylesheet" href="../doc/docs.css">
<style type="text/css">
.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}
</style>
</head>
<body>
<h1>CodeMirror: Lazy Mode Loading</h1>
<form><textarea id="code" name="code">This is the editor.
// It starts out in plain text mode,
# use the control below to load and apply a mode
"you'll see the highlighting of" this text /*change*/.
</textarea></form>
<p><input type=text value=javascript id=mode> <button type=button onclick="change()">change mode</button></p>
<script>
CodeMirror.modeURL = "../mode/%N/%N.js";
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true
});
var modeInput = document.getElementById("mode");
CodeMirror.connect(modeInput, "keypress", function(e) {
if (e.keyCode == 13) change();
});
function change() {
editor.setOption("mode", modeInput.value);
CodeMirror.autoLoadMode(editor, modeInput.value);
}
</script>
</body>
</html>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Breakpoint Demo</title>
<link rel="stylesheet" href="../lib/codemirror.css">
<script src="../lib/codemirror.js"></script>
<script src="../mode/javascript/javascript.js"></script>
<link rel="stylesheet" href="../doc/docs.css">
<style type="text/css">
.CodeMirror-gutter {
width: 3em;
background: white;
}
.CodeMirror {
border: 1px solid #aaa;
}
</style>
</head>
<body>
<h1>CodeMirror: Breakpoint demo</h1>
<form><textarea id="code" name="code">
CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
onGutterClick: function(cm, n) {
var info = cm.lineInfo(n);
if (info.markerText)
cm.clearMarker(n);
else
cm.setMarker(n, "<span style=\"color: #900\">●</span> %N%");
}
});
</textarea></form>
<p>Click the line-number gutter to add or remove 'breakpoints'.</p>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
onGutterClick: function(cm, n) {
var info = cm.lineInfo(n);
if (info.markerText)
cm.clearMarker(n);
else
cm.setMarker(n, "<span style=\"color: #900\">●</span> %N%");
}
});
</script>
</body>
</html>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Match Highlighter Demo</title>
<link rel="stylesheet" href="../lib/codemirror.css">
<script src="../lib/codemirror.js"></script>
<script src="../lib/util/searchcursor.js"></script>
<script src="../lib/util/match-highlighter.js"></script>
<link rel="stylesheet" href="../doc/docs.css">
<style type="text/css">
.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}
span.CodeMirror-matchhighlight { background: #e9e9e9 }
.CodeMirror-focused span.CodeMirror-matchhighlight { background: #e7e4ff; !important }
</style>
</head>
<body>
<h1>CodeMirror: Match Highlighter Demo</h1>
<form><textarea id="code" name="code">Select this text: hardToSpotVar
And everywhere else in your code where hardToSpotVar appears will automatically illuminate.
Give it a try! No more hardToSpotVars.</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers : true,
onCursorActivity: function() {
editor.matchHighlight("CodeMirror-matchhighlight");
}
});
</script>
<p>Highlight matches of selected text on select</p>
</body>
</html>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Multiplexing Parser Demo</title>
<link rel="stylesheet" href="../lib/codemirror.css">
<script src="../lib/codemirror.js"></script>
<script src="../lib/util/multiplex.js"></script>
<script src="../mode/xml/xml.js"></script>
<link rel="stylesheet" href="../doc/docs.css">
<style type="text/css">
.CodeMirror {border: 1px solid black;}
.cm-delimit {color: #fa4;}
</style>
</head>
<body>
<h1>CodeMirror: Multiplexing Parser Demo</h1>
<form><textarea id="code" name="code">
<html>
<body style="<<magic>>">
<h1><< this is not <html >></h1>
<<
multiline
not html
at all : &amp;amp; <link/>
>>
<p>this is html again</p>
</body>
</html>
</textarea></form>
<script>
CodeMirror.defineMode("demo", function(config) {
return CodeMirror.multiplexingMode(
CodeMirror.getMode(config, "text/html"),
{open: "<<", close: ">>",
mode: CodeMirror.getMode(config, "text/plain"),
delimStyle: "delimit"}
// .. more multiplexed styles can follow here
);
});
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
mode: "demo",
lineNumbers: true,
lineWrapping: true
});
</script>
<p>Demonstration of a multiplexing mode, which, at certain
boundary strings, switches to one or more inner modes. The out
(HTML) mode does not get fed the content of the <code>&lt;&lt;
>></code> blocks. See
the <a href="../doc/manual.html#util_multiplex">manual</a> and
the <a href="../lib/util/multiplex.js">source</a> for more
information.</p>
</body>
</html>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Overlay Parser Demo</title>
<link rel="stylesheet" href="../lib/codemirror.css">
<script src="../lib/codemirror.js"></script>
<script src="../lib/util/overlay.js"></script>
<script src="../mode/xml/xml.js"></script>
<link rel="stylesheet" href="../doc/docs.css">
<style type="text/css">
.CodeMirror {border: 1px solid black;}
.cm-mustache {color: #0ca;}
</style>
</head>
<body>
<h1>CodeMirror: Overlay Parser Demo</h1>
<form><textarea id="code" name="code">
<html>
<body>
<h1>{{title}}</h1>
<p>These are links to {{things}}:</p>
<ul>{{#links}}
<li><a href="{{url}}">{{text}}</a></li>
{{/links}}</ul>
</body>
</html>
</textarea></form>
<script>
CodeMirror.defineMode("mustache", function(config, parserConfig) {
var mustacheOverlay = {
token: function(stream, state) {
var ch;
if (stream.match("{{")) {
while ((ch = stream.next()) != null)
if (ch == "}" && stream.next() == "}") break;
stream.eat("}");
return "mustache";
}
while (stream.next() != null && !stream.match("{{", false)) {}
return null;
}
};
return CodeMirror.overlayMode(CodeMirror.getMode(config, parserConfig.backdrop || "text/html"), mustacheOverlay);
});
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {mode: "mustache"});
</script>
<p>Demonstration of a mode that parses HTML, highlighting
the <a href="http://mustache.github.com/">Mustache</a> templating
directives inside of it by using the code
in <a href="../lib/util/overlay.js"><code>overlay.js</code></a>. View
source to see the 15 lines of code needed to accomplish this.</p>
</body>
</html>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: HTML5 preview</title>
<script src=../lib/codemirror.js></script>
<script src=../mode/xml/xml.js></script>
<script src=../mode/javascript/javascript.js></script>
<script src=../mode/css/css.js></script>
<script src=../mode/htmlmixed/htmlmixed.js></script>
<link rel=stylesheet href=../lib/codemirror.css>
<link rel=stylesheet href=../doc/docs.css>
<style type=text/css>
.CodeMirror {
float: left;
width: 50%;
border: 1px solid black;
}
iframe {
width: 49%;
float: left;
height: 300px;
border: 1px solid black;
border-left: 0px;
}
</style>
</head>
<body>
<h1>CodeMirror: HTML5 preview</h1>
<textarea id=code name=code>
<!doctype html>
<html>
<head>
<meta charset=utf-8>
<title>HTML5 canvas demo</title>
<style>p {font-family: monospace;}</style>
</head>
<body>
<p>Canvas pane goes here:</p>
<canvas id=pane width=300 height=200></canvas>
<script>
var canvas = document.getElementById('pane');
var context = canvas.getContext('2d');
context.fillStyle = 'rgb(250,0,0)';
context.fillRect(10, 10, 55, 50);
context.fillStyle = 'rgba(0, 0, 250, 0.5)';
context.fillRect(30, 30, 55, 50);
</script>
</body>
</html></textarea>
<iframe id=preview></iframe>
<script>
var delay;
// Initialize CodeMirror editor with a nice html5 canvas demo.
var editor = CodeMirror.fromTextArea(document.getElementById('code'), {
mode: 'text/html',
tabMode: 'indent',
onChange: function() {
clearTimeout(delay);
delay = setTimeout(updatePreview, 300);
}
});
function updatePreview() {
var previewFrame = document.getElementById('preview');
var preview = previewFrame.contentDocument || previewFrame.contentWindow.document;
preview.open();
preview.write(editor.getValue());
preview.close();
}
setTimeout(updatePreview, 300);
</script>
</body>
</html>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Autoresize Demo</title>
<link rel="stylesheet" href="../lib/codemirror.css">
<script src="../lib/codemirror.js"></script>
<script src="../mode/css/css.js"></script>
<link rel="stylesheet" href="../doc/docs.css">
<style type="text/css">
.CodeMirror {
border: 1px solid #eee;
}
.CodeMirror-scroll {
height: auto;
overflow-y: hidden;
overflow-x: auto;
}
</style>
</head>
<body>
<h1>CodeMirror: Autoresize demo</h1>
<form><textarea id="code" name="code">
.CodeMirror-scroll {
height: auto;
overflow-y: hidden;
overflow-x: auto;
}</textarea></form>
<p>By setting a few CSS properties, CodeMirror can be made to
automatically resize to fit its content.</p>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true
});
</script>
</body>
</html>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Mode Runner Demo</title>
<link rel="stylesheet" href="../lib/codemirror.css">
<script src="../lib/codemirror.js"></script>
<script src="../lib/util/runmode.js"></script>
<script src="../mode/xml/xml.js"></script>
<link rel="stylesheet" href="../doc/docs.css">
</head>
<body>
<h1>CodeMirror: Mode Runner Demo</h1>
<textarea id="code" style="width: 90%; height: 7em; border: 1px solid black; padding: .2em .4em;">
<foobar>
<blah>Enter your xml here and press the button below to display
it as highlighted by the CodeMirror XML mode</blah>
<tag2 foo="2" bar="&amp;quot;bar&amp;quot;"/>
</foobar></textarea><br>
<button onclick="doHighlight();">Highlight!</button>
<pre id="output" class="cm-s-default"></pre>
<script>
function doHighlight() {
CodeMirror.runMode(document.getElementById("code").value, "application/xml",
document.getElementById("output"));
}
</script>
<p>Running a CodeMirror mode outside of the editor.
The <code>CodeMirror.runMode</code> function, defined
in <code><a href="../lib/util/runmode.js">lib/runmode.js</a></code> takes the following arguments:</p>
<dl>
<dt><code>text (string)</code></dt>
<dd>The document to run through the highlighter.</dd>
<dt><code>mode (<a href="../doc/manual.html#option_mode">mode spec</a>)</code></dt>
<dd>The mode to use (must be loaded as normal).</dd>
<dt><code>output (function or DOM node)</code></dt>
<dd>If this is a function, it will be called for each token with
two arguments, the token's text and the token's style class (may
be <code>null</code> for unstyled tokens). If it is a DOM node,
the tokens will be converted to <code>span</code> elements as in
an editor, and inserted into the node
(through <code>innerHTML</code>).</dd>
</dl>
</body>
</html>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Search/Replace Demo</title>
<link rel="stylesheet" href="../lib/codemirror.css">
<script src="../lib/codemirror.js"></script>
<script src="../mode/xml/xml.js"></script>
<script src="../lib/util/dialog.js"></script>
<link rel="stylesheet" href="../lib/util/dialog.css">
<script src="../lib/util/searchcursor.js"></script>
<script src="../lib/util/search.js"></script>
<link rel="stylesheet" href="../doc/docs.css">
<style type="text/css">
.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}
dt {font-family: monospace; color: #666;}
</style>
</head>
<body>
<h1>CodeMirror: Search/Replace Demo</h1>
<form><textarea id="code" name="code">
<dt id="option_indentWithTabs"><code>indentWithTabs (boolean)</code></dt>
<dd>Whether, when indenting, the first N*8 spaces should be
replaced by N tabs. Default is false.</dd>
<dt id="option_tabMode"><code>tabMode (string)</code></dt>
<dd>Determines what happens when the user presses the tab key.
Must be one of the following:
<dl>
<dt><code>"classic" (the default)</code></dt>
<dd>When nothing is selected, insert a tab. Otherwise,
behave like the <code>"shift"</code> mode. (When shift is
held, this behaves like the <code>"indent"</code> mode.)</dd>
<dt><code>"shift"</code></dt>
<dd>Indent all selected lines by
one <a href="#option_indentUnit"><code>indentUnit</code></a>.
If shift was held while pressing tab, un-indent all selected
lines one unit.</dd>
<dt><code>"indent"</code></dt>
<dd>Indent the line the 'correctly', based on its syntactic
context. Only works if the
mode <a href="#indent">supports</a> it.</dd>
<dt><code>"default"</code></dt>
<dd>Do not capture tab presses, let the browser apply its
default behaviour (which usually means it skips to the next
control).</dd>
</dl></dd>
<dt id="option_enterMode"><code>enterMode (string)</code></dt>
<dd>Determines whether and how new lines are indented when the
enter key is pressed. The following modes are supported:
<dl>
<dt><code>"indent" (the default)</code></dt>
<dd>Use the mode's indentation rules to give the new line
the correct indentation.</dd>
<dt><code>"keep"</code></dt>
<dd>Indent the line the same as the previous line.</dd>
<dt><code>"flat"</code></dt>
<dd>Do not indent the new line.</dd>
</dl></dd>
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {mode: "text/html", lineNumbers: true});
</script>
<p>Demonstration of primitive search/replace functionality. The
keybindings (which can be overridden by custom keymaps) are:</p>
<dl>
<dt>Ctrl-F / Cmd-F</dt><dd>Start searching</dd>
<dt>Ctrl-G / Cmd-G</dt><dd>Find next</dd>
<dt>Shift-Ctrl-G / Shift-Cmd-G</dt><dd>Find previous</dd>
<dt>Shift-Ctrl-F / Cmd-Option-F</dt><dd>Replace</dd>
<dt>Shift-Ctrl-R / Shift-Cmd-Option-F</dt><dd>Replace all</dd>
</dl>
<p>Searching is enabled by
including <a href="../lib/util/search.js">lib/util/search.js</a>
and <a href="../lib/util/searchcursor.js">lib/util/searchcursor.js</a>.
For good-looking input dialogs, you also want to include
<a href="../lib/util/dialog.js">lib/util/dialog.js</a>
and <a href="../lib/util/dialog.css">lib/util/dialog.css</a>.</p>
</body>
</html>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Theme Demo</title>
<link rel="stylesheet" href="../lib/codemirror.css">
<script src="../lib/codemirror.js"></script>
<link rel="stylesheet" href="../theme/neat.css">
<link rel="stylesheet" href="../theme/elegant.css">
<link rel="stylesheet" href="../theme/erlang-dark.css">
<link rel="stylesheet" href="../theme/night.css">
<link rel="stylesheet" href="../theme/monokai.css">
<link rel="stylesheet" href="../theme/cobalt.css">
<link rel="stylesheet" href="../theme/eclipse.css">
<link rel="stylesheet" href="../theme/rubyblue.css">
<link rel="stylesheet" href="../theme/lesser-dark.css">
<link rel="stylesheet" href="../theme/xq-dark.css">
<link rel="stylesheet" href="../theme/ambiance.css">
<link rel="stylesheet" href="../theme/blackboard.css">
<link rel="stylesheet" href="../theme/vibrant-ink.css">
<script src="../mode/javascript/javascript.js"></script>
<link rel="stylesheet" href="../doc/docs.css">
<style type="text/css">
.CodeMirror {border: 1px solid black; font-size:13px}
</style>
</head>
<body>
<h1>CodeMirror: Theme demo</h1>
<form><textarea id="code" name="code">
function findSequence(goal) {
function find(start, history) {
if (start == goal)
return history;
else if (start > goal)
return null;
else
return find(start + 5, "(" + history + " + 5)") ||
find(start * 3, "(" + history + " * 3)");
}
return find(1, "1");
}</textarea></form>
<p>Select a theme: <select onchange="selectTheme()" id=select>
<option selected>default</option>
<option>ambiance</option>
<option>blackboard</option>
<option>cobalt</option>
<option>eclipse</option>
<option>elegant</option>
<option>erlang-dark</option>
<option>lesser-dark</option>
<option>monokai</option>
<option>neat</option>
<option>night</option>
<option>rubyblue</option>
<option>vibrant-ink</option>
<option>xq-dark</option>
</select>
</p>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true
});
var input = document.getElementById("select");
function selectTheme() {
var theme = input.options[input.selectedIndex].innerHTML;
editor.setOption("theme", theme);
}
var choice = document.location.search && document.location.search.slice(1);
if (choice) {
input.value = choice;
editor.setOption("theme", choice);
}
</script>
</body>
</html>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Vim bindings demo</title>
<link rel="stylesheet" href="../lib/codemirror.css">
<script src="../lib/codemirror.js"></script>
<script src="../mode/clike/clike.js"></script>
<script src="../keymap/vim.js"></script>
<script src="../lib/util/dialog.js"></script>
<link rel="stylesheet" href="../doc/docs.css">
<link rel="stylesheet" href="../lib/util/dialog.css">
<style type="text/css">
.CodeMirror {border-top: 1px solid #eee; border-bottom: 1px solid #eee;}
</style>
</head>
<body>
<h1>CodeMirror: Vim bindings demo</h1>
<form><textarea id="code" name="code">
#include "syscalls.h"
/* getchar: simple buffered version */
int getchar(void)
{
static char buf[BUFSIZ];
static char *bufp = buf;
static int n = 0;
if (n == 0) { /* buffer is empty */
n = read(0, buf, sizeof buf);
bufp = buf;
}
return (--n >= 0) ? (unsigned char) *bufp++ : EOF;
}
</textarea></form>
<p>The vim keybindings are enabled by
including <a href="../keymap/vim.js">keymap/vim.js</a> and setting
the <code>keyMap</code> option to <code>"vim"</code>. Because
CodeMirror's internal API is quite different from Vim, they are only
a loose approximation of actual vim bindings, though.</p>
<script>
CodeMirror.commands.save = function(){ alert("Saving"); };
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
mode: "text/x-csrc",
keyMap: "vim"
});
</script>
</body>
</html>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Visible tabs demo</title>
<link rel="stylesheet" href="../lib/codemirror.css">
<script src="../lib/codemirror.js"></script>
<script src="../mode/clike/clike.js"></script>
<link rel="stylesheet" href="../doc/docs.css">
<style type="text/css">
.CodeMirror {border-top: 1px solid #eee; border-bottom: 1px solid #eee;}
.cm-tab {
background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAMCAYAAAAkuj5RAAAAAXNSR0IArs4c6QAAAGFJREFUSMft1LsRQFAQheHPowAKoACx3IgEKtaEHujDjORSgWTH/ZOdnZOcM/sgk/kFFWY0qV8foQwS4MKBCS3qR6ixBJvElOobYAtivseIE120FaowJPN75GMu8j/LfMwNjh4HUpwg4LUAAAAASUVORK5CYII=);
background-position: right;
background-repeat: no-repeat;
}
</style>
</head>
<body>
<h1>CodeMirror: Visible tabs demo</h1>
<form><textarea id="code" name="code">
#include "syscalls.h"
/* getchar: simple buffered version */
int getchar(void)
{
static char buf[BUFSIZ];
static char *bufp = buf;
static int n = 0;
if (n == 0) { /* buffer is empty */
n = read(0, buf, sizeof buf);
bufp = buf;
}
return (--n >= 0) ? (unsigned char) *bufp++ : EOF;
}
</textarea></form>
<p>Tabs inside the editor are spans with the
class <code>cm-tab</code>, and can be styled.
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
tabSize: 4,
indentUnit: 4,
indentWithTabs: true,
mode: "text/x-csrc"
});
</script>
</body>
</html>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: XML Autocomplete Demo</title>
<link rel="stylesheet" href="../lib/codemirror.css">
<script src="../lib/codemirror.js"></script>
<script src="../lib/util/simple-hint.js"></script>
<link rel="stylesheet" href="../lib/util/simple-hint.css">
<script src="../lib/util/closetag.js"></script>
<script src="../lib/util/xml-hint.js"></script>
<script src="../mode/xml/xml.js"></script>
<link rel="stylesheet" href="../doc/docs.css">
<style type="text/css">.CodeMirror {border: 1px solid #eee;} .CodeMirror-scroll { height: 100% }</style>
</head>
<body>
<h1>CodeMirror: XML Autocomplete demo</h1>
<form><textarea id="code" name="code"></textarea></form>
<p>Type '&lt;' or space inside tag or
press <strong>ctrl-space</strong> to activate autocompletion. See
the code (<a href="../lib/util/simple-hint.js">here</a>
and <a href="../lib/util/xml-hint.js">here</a>) to figure out how
it works.</p>
<script>
CodeMirror.xmlHints['<'] = [
'levelTop',
'levelRoot',
'mainLevel'
];
CodeMirror.xmlHints['<levelTop '] =
CodeMirror.xmlHints['<levelRoot '] =
CodeMirror.xmlHints['<mainLevel '] = [
'property1111',
'property2222'
];
CodeMirror.xmlHints['<levelTop><'] =
CodeMirror.xmlHints['<levelRoot><'] =
CodeMirror.xmlHints['<mainLevel><'] = [
'second',
'two'
];
CodeMirror.xmlHints['<levelTop><second '] = [
'secondProperty'
];
CodeMirror.xmlHints['<levelTop><second><'] = [
'three',
'x-three'
];
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
value: '',
mode: 'text/html',
lineNumbers: true,
extraKeys: {
"'>'": function(cm) { cm.closeTag(cm, '>'); },
"'/'": function(cm) { cm.closeTag(cm, '/'); },
"' '": function(cm) { CodeMirror.xmlHint(cm, ' '); },
"'<'": function(cm) { CodeMirror.xmlHint(cm, '<'); },
"Ctrl-Space": function(cm) { CodeMirror.xmlHint(cm, ''); }
}
});
</script>
</body>
</html>
�PNG

IHDR{��P�sBIT|d� pHYsTT�`�tEXtSoftwarewww.inkscape.org��< IDATx��w|U��w���@H�$@"��@�P�� %tDzQQE�£�<�J�G�HP"E�:R��N!��M�9��]�dwgfwvg����9wo93s��;��{.#"(�1�T� ��Ҝ���^s��8ʭ��0���T����قj�P������Thc�s
�a��AߠW��M�j�z�R!�=c�@<5�Z �$�j�D��J���eQD���((؊re�c���Q��ɨ�)�ʭ@e�d��y��H$�#rꥠ`k���3��tЩDʩ���2�܈(OnE* ���b��n� $�lS�dƮ�=c,��=\N}$B�m�܊Tdcx:z�O��+T*d5���@��r�c....P�զ�4�b�%�1��+8��ܤ�c�P����/q�t�S���-�___�h��:uB�V���s�!00���ƃ�eU���k ΰ� �M�_�D)�r�Ս=c���b��ְk�����;�e˖ C�5���b4O˖-���Z1�fP�ʪ3��g�HX� ��iǵBD�%,_A�����g���3��V?�%�k�FTT:t��͛�~��^�:���;u�d��+�/E��0�`�a-���At�z�������(�J�+(�Ɍ=c� 8��@3�ʵ�J���DGG#:: A�j����7�'��-[��:�1V��KVa�1��:p�lM��J�1v O�� 爨H�,�Y�1�<���e��;::",, :t@۶mѴiSԩS>>>P��y����p��5���?�p�.^����B̝;���3��Ν;�SǤ��E"�/J�Jc�]��e�)�M���8��MY5RP�hc� 0�@��P����`���kh׮7n�ڵk��� ����j\�rEg�/^����\4o�AAA���AFF�NT*fϞ�ڵk�)�����O��D�@ܕVJ6�-��uy#�x"�MnE�!�ؗ,s�ȿ`m�J�R�ТE 4]�vE� ���&����|\�|YϨ_�pׯ_�F�)����QQQx饗0f��������ƾ���ƉR����@�_���mc�h�܊((�¨�/�f� �(p~xw[(���_| @tt4�������򐘘�g�/^��7n����,}\\\����>@x��=^]�v�_�e��cDd�J{�1�0���e��L%�'r+���Gc� 0�pu�����?z��^�z�U�V������3�K��ի8v�.\��3�7o�4ۨ���믿� ����`���_���O���7�x�@�����\:T �����
�#"0�����G�[�l��b 6ĀХK������&�!!!��IJJ��T4IHHV�^�v�ڕ�n�Ν�޽���u��+y����S�
�<"z_n%��,0 ���8;;�^�����f͚�N�:�S�<<<L������c�t��رc��ΖZ=^c:�Mzz:��ӡV������?�3g΄���ի7n�@���M�m����0�j8��Upr��щ{�@$2���ވ��Btt45j���04h��ΦW�=|�Po�~��ɿ�944��9���s+���"==iiiHKKC�5t��l
@vcn���r<L�܊((��|
n�L4~~~���D�-ШQ#<���hЀ?��իW���+�O�stt���?rss������BsTE�Ν�|�r�u���U�"33����h��ʉ�$|�_�vQ��,�D�!�"
�`�8ėP�R���h֬^x��k����B�?����/bbbШQ#4j� 6DXX�^8���dgg#33/^ę3g������ܸqR͇zyya޼y=z��t���8|�/�l�J�X�ic�(�ѿ�VBA�Gp�2%_}������ٴg����ϩk׮T�J�����(Z�r%�����g���Lڱc�=��U�&ZCҷo_*((0Z��l*!g"��@c�����TU�x��("T��p~d� z���d������_i���I���fw�!C�PBB��z,����v��Ecƌ!___�:��A�H���g�֭|�{�p��ځQ��򁭟�"���?�{|�9""�����ѨQ��瞓������Ν;�VdffҤI�,�az��7 �}��e��CȖ�s�e؁1�����-��"���?\^���1F����%88���R���ޣ��l����:v�h��3g�,Sfvv6_���.�@���" </� �������D��-%�[O��'O���ݸq#i1b�E��ёV�^M���ɓ;����Ly����đ-,�@���$�8������, _*�sv� W�G�(?
�H O�V�5�Ү��+W��)\\\h�֭d/���Qxx�Y����H���z�j��T�[d�
P`Ư2ʯ��<�F���(���X<�Qp�v�R�|��?�x8&x8i�}�ٍ6..��#G��J�2�z^y����L�—Ǜ��@��XdFO�$6�R����\�Yކt��=�*�!zxxPqq1�#cǎ5���ڵKW�����ҷ#k<L�m�v`l�W�p�FS���'"��w+�}�t���|�ː�������l���~�w�Q�Ν��q��|�%?��16 �BX1��B�a)�0�x���=|��ݫ��cOD8{���|��V�Zx��7� CXwT�޽{QPPO�zIw�2�:�-e�
\8��U�ʭ�X��In%��{������g f̘�*U�J�V���?���~@@@������'_�7�G�r�]�pqqATT�{�=L�6 ������+22�]ț����`��>Uh���q�i1gK���ɞ� y�'���;q+zJ��iҤ��|i$�/\ ;����J�իGC� �����?N�����_R�F�d����#�X�'�ղe�H�[o�eV�<s� �+������-�:�]����7���[��z��k�܆�n��ۛ�v�J�|� m۶�>|HDD���4�|����]G �_�ږ"G�~���5٠� BZ6n�hV����ɞ�1c���prr����2���g���H���#c���@4n�8�駟�… z��233iŊC��k%9�_���H�Cg�v�(�����> 555j�����&*���IMMEpp0rssyӮ_� ��,!!-Z�0��C"�eZr0�.�?H@fT*\\\�"����U�Z�j�wZff&>���x�����ɓ69���+q�� {��Le�x�"6lh֬�nrR {��A�.]D�˃��~8pē'O���3�ƍÄ ��2e
���[���իW�}���___S�~&�7D^�Ac9ܥ(�\Z�h�������Ӡ!vqq�;��Z<|�D||<<��g�Z��r�-]��܊(�O��GDj��a]Meܻw��ؿ��f� Z��/Y�o����4G�5h�?��,^�j��d������jժppp�F�1�M�嗌�j��п��kX�f <<<0o�<���C�Ѡ���࿦��$MVV�]�&筰7�d�u%��r+� 3�|;���/طo_�" ��Q��[�HJ�������_e� �-ZP۶m�k׮&�&L� �ZJG��:�Y��ܜ{/�����z��#""��W+RVhii[S�|����.L6 ___��WZZ��qe�O�NB��̤C���ŋi�ܹe��b=ݩՒ
�_�}���A^^^ԫW/Z�d %%% ���())IP����L^�A� �1����ё~��2�#�aSİd�Ja:)b�Cn��c�t��i�ҲeK�������1233iʔ)����ɉ222���8/�RߞAI�$�m�fTp񊮌��B�� !66��:�͛W&߲e�����L ��lm8�V�Jqqqt��u:t�9rDw�Æ �ۨ)b\��M��nx��<��@D���4R�}��6l�`�5k� <<����͛7��+,,Ď;���ɢ��4)��h�S?���mڴ�Ms���2�5k֌/�;iyc3HMvv6z������w�A�:���ǏǶm�l���p<�1�zʭ���1h�K:�s��f+�5�Z.^��_|C�Ń���]�6&L����8��� �Z�̂� (�}�l�JӼys�4w�]�—�\�"n7~Ϟ=q��AԬY���G׮]�cx�ʆ �͌�Ar+�`c� �������S�"���2�L����Si���W&��ѣ��ٳd��b��Q_���J���>|�֬Yc�}T���^C�F���+**"Ƙ�|�,}5p��{n����{����۷�����.
Eĉ�(K۟"�GL ��k4G�%-mڴ1�����Riv�ء�f͚�c���^�����W^/�n�ܹ�����x��d��V�j0_ݺu�:����/Dܰ��ppp�� �oӦM���$��R�<)�֒��H�Sn�g'- ����M/111�S�����ϣ[�n�er���=���]z�ӱc����ϕ���ap�m�֭MeS� ~o �P���b���Ķm����oV�Z��V��`��J(�>co���čP�*�R����X�b��x↌=嫑��!�φ�O>��~�-&L� $�<a~{m�Ҵoߞ/�%~�N�L�ڵq��!t���YmĈ�6�)��(��J��a?��9����U�����1����^#�h�]j�^�[7N)u��6Ķm�x�c���e�:t�/߷d�k��b�9��������u�4g����H+IP*��brdOD��������G����-S|1�K���ХK���S�N���8�>�#7n�`��L Ѯ];p^��׫W��jKF�V_�ӭ[7���#00��g���?�v�
�%�{r+�`]��8� \9b��ڵk�w�^8��k������������� &����F�޽�s�N�i|||xϖ�w��RO???�y`��>""7n��;zgʔ)�5k�5��4888ȭ³�`�U�[ �!��[}�V��g�! ���
�m�bn�p�S�`���h�eسgZ�l�m۶a���&뎎�6���#j�4�W 5c5Ll��l۶ U�TAqq1Ə/(��04h d `K�|.�
V���n�]L��(;;�����Į�~v���$wb�oҒBCCi���4}�t���o������E�zzxzzR^^���W�^m�:ڵkg0�k���w:�=#�f���,T����ĉDą�:t��>�
)�|��R �5)b�"Ԩ��5��k�_|�EQ�l�ĉ$�'}j��'!��k��˯��j��7o��p�B�|�|� _���<����1F7n$""�ZM�{���\;0fv%��3gʮ�3�9mQ�!n��~{Q��Ԡ���^v�0�]iL�r���y�j���e>kٲ%_���?��(_~�%�����\���[�n�����h{�Q�ΦM�0h� ���˩�������1��P+�5B��U���i<x`r� ��_���#A����!''���|~�����z���^)T
s�}8���B&X�o��3f�ɓ'�֭���O��S�T����q��]�gW�h4X�`�-[ƻ�KU�T1'��������(�B���N�ʂ��?�JE���DDTPP@���_��w�����Cw��)�]jj*����кu�*3�ƹ�@
t�"H��k��cѢE��ǎ��G�V���F�����B�1���&�ZM�?���H��nnn�y�f!��Z\]])99��|�MI��ҥ�9y��6PľDxB`_�ٲe is����lj���$�C3z��MS�L�O?�:u�7ɵ�n �~�7<M����B�w��F�8wk7n��j]>???�<��~�@K�D�z��ѣG���LM�6���x{{ӑ#Gh޼yV1�M>��#�~�$eu�ؑ���+6_�@���"�� �M&�;�CZ��� nlB�&,((tִ�����-��t��j�"�3���h4��[�C2f�]>?~��~�@Ms�CժU)11�n߾�w����N�8A׮]#777� bEoooJKK� 6,�E��^$`���H�P�=`%����� ����j��_�~0�����^*]y�������������j��*�
����z��#Gt������ f@ND���3*
GGGlܸNNNh߾=�\��5j����,=|||�g�DFFbܸq����Ϥ���L��㏨_��1|��'X�t)Z�h!&�HI*W�_��2x�BJJ
q�==M�MPDD E�/����N����7��&c��V�J�aÆ��=z� ��+������FK��κx�����K�ޒ_m���TZ�.]JDD���t��)��ʢ��B�Y���Ѥ���nm���yF�{�7l�0�w����Ɩ#MEl+bF�����}�p�F�B�Q����6�� ������7�'"xyy�i��h�ݻw��c�o �۷Gpp0���~�[������%��Ԫ3bO�4 �Ǐ�]O˖-��鉍7 ��Ǽy����d|����Wv<x��'OJV��ի���l޼���B�)��
�Xc/�Q�b��v���T �r3__ߧJ���2:�.�~<==p�iS���۷� Baa!>��c�e0�0|�p^}]]]u!����1��[�q�=z`�ܹ� $�Ŝ� �[oqg�N�8Q9��L=�3
����GTT�,Y"4� Ƙ�dJ(�b^���5�*JZN�:e2-c�n߾MD��IC�*K� �[zeKHH� �>swq�Du� �,�v�ں�Ə��?w�\rpp �8p��.T�zu�W�U�V��h�F&����h���5mڔ���K3gΤ���?�N�Ç��2HHH "�cǎ��QD_�+��~�m�y�¥���E|�2_��p�FC>>>F�u�ܙ��V�\IիW�3gΐ)~��@�=��.n~�V�5i҄���ue����O�+I��K/�<y2yxx0`��Ӈ�G��Y������O�Fl߾=_�af?Hns�>}J��R��ު#Cg��IժUug�~��'�7E�%,,�
(//��ի'$ϟr%E�#b�8�W�J�B���kӦ :w��Ç#55���u�dee�v�V��Ee�z�*^x�]ڿ���Gt�1Ѻr��كA��{�oߎ/��^^^�|�2���,g„ h֬�I�uw���dZX�'"���N�V��6l�n��֭[زe��z۶m�s��رCt~�r��U,^�����?��,]cV?'A��X������g��M�zzz�.������<~� 6��svv�Z�֛��]��'�WV~N�U����G�kvv6fϞ��K��̙�s�Ε)��� �����%��.]Ҏ��,15{�e �&i�g��� �:bP�����ӧO�ί`}f͚���t����ٳ'_r�7l����1���L�Q���F��5��C4
u��)))�CE��|x����(0ZV;���pp� <p��i�J�5k�����;v,
1f��q�����e��Z�g�����;wX��*@���ԩ��eggcٲefU�������`?���a�ʕ��ӧ �2š�(ȃhcODN�Js��]\�zФI=#l S�-Zc@7��s��0pGGG����~@�g <Q��֕�h׮�Ν �����_�u��hذ!���o�Z��`9m۶����F�x�"�Q#��R�c��h�l�K����'dff�U��9�9#�B�����j�ﴵBc�������:u��[`LL o�x�޽{������K����A�Bm����m�B�P�Z5L�:���:�����u��E�-�M�68q�A��o_�N�k0�%�����%�Y�&z�� �;%L�/� �琐�;]� #@QQ���$$�+��`c�n��� NNNB&/�F�ډł��a؉��h׮�.M��{��1�W���aʔ)`�aڴi2d �~r. IDAT55�����'O���6Z^�:up���2~Q��g� �]n�$�X�L�?~��8�m۶�6~��vd�{��ɓ'�M[u���ecL�!
�s��a&��۷O����\աCA��K{GGGݮYm�7n��A��&� wx�!_���իu�J<�]�zUW7��*U�`�֭���u��^��ݼe���D�0���ӝ��1n�8��[z����RRR���lQ9
�G��qq�w�
�~��G���e�H ���ѣG8�< <<��J�I�& ����Z��������2��F2��2�
o�˟��'''��� ..N�پ}�.�Ժu됞�nRO�J����+V������gpM�`�$-��@_��.66V�z9s� ����+���۶@c(�*���\9͚5C�=U���[������U�պp Ϯ����KF�5�E�\�|9Z�h���\]l�'O��ɓ'���<�X�B��Çǟ����|<|�tKFM`��K偋s�7�>q�D���}����8;;�ʕ+��
X��`E�9���|1�r:0Ɣ�VA���Ϙ1CT�ժqǮ����ۛ x����[c����� 6�{0L�#����s�h�L����u/]�T�2Î;b˖-�|�2A+r����BDY��-Z�@۶m���X�n�E�kG�B�}���eQ}
������'O�Y"� ��J
6�c@�����:��}XX���'x��v_zd����3�ׯ_/�f��p�Ě{x nhn׭�0����/�ʕ+F#bjIOO׭ˏ����W�^=!���r�Q*���^n�x�b��'|�1��g���W�8s��3� 0�Iq@���m쉨�+�ddd��_����6Bi�~�:BBBгgO��S�6��F�׮]3�A�g��Z`#�c|у\��7*�� �iiih֬6o� "Bݺup��<��s|�)��"��Ґ!C��O�;���>c_�NDEE�ҥKש`�O�.锇`�N"R�k,��rJ�H6l��
����� .�܁<�/��Քȳ8� �<Uq50U������� � v�ׯ���"22'N��}'��#�������nnns.ֹ�tSSSq��Qܺu�d��Ν;bG�
V�̙3b�=�L�Vd5�Z��@�g_ڍ�]9���777���gܧ!#��fH�sx���D��MW^P�}xb?j�����k0`�ԩS�۷��s��%7�%�%��RL�j5joL���-?U���/� ��>
��"cOD���:tH�)ɘ���������:�#�,�����w��Ug���G������~������7� ��K���G��'$$���ۼ����_�p��=dee��2�1��[�x����w�… ��� A�V����*�Gaa�9ounZAb���9�0''Ǐ� 3��NLKZc�u�V���kpss�իW�n�:�A����G�*p�,��Ow<�!�Q��P�A�������o���h4�|����Ӎ�Q�����#��X�-[��"u��hժ(#����P� )��Ů��:@7b�������u��Y�f�=݆.-�ᄭ������(@w��u��#�$��#��x:�^�l�^lxc|��Wpr�V�hG�aaa�p&�ԕS`m- {��m�-�ؗ{�2�x_I��F�&��{�1B۶mu!,X�A��1�۷o���˺���$� %
�؂jh
��lE�1j@������@�R?z��ׯ�շ~��0a�����Y��^j��OE���W�8�a]�{"z�Si�;��<nc�!c_TT$�N�����Ŗ-[Э[7�Z���Do��_����7,A6V�~Gu��*h��
��,\�P��3g΄�����V�NZɌ=cl0��R�'�&M� ??�7Ą���<!R�)F���^�V��a���Yg����믿� ����C����#RRR�k�.��8����˼ �C�B:f ���*`� �� o%O���Y���� ���燥K��{[-�,��e�����r�I� �$ȞB9E*co�Q�b������W_PP���_���իz���i�̯�{J4� G<���
_��jb��e�&7k�L� [0h� t��I��`�Cc�@�� @Љ��������l�[ː���0i�M���{�s�h �vD�l�'?�VjR� ���> �������,
����iӦ������m@��a�&(�l�z�{/���Sn%,CcOD���Js��I�:�gO��8���M�t!��<yR&�K�Ǡig�+q �S1�{�9t�nݺ8P��cwww��lxxx��_���3ƺ�[�J(ƾB���L�Q�{��<��F���x��F�����7}V�1�7on��k(2��4X16��!ŏ��Sօ3u�T��v�ڥs-i ����nS� ,���:��XE�J�r��©Hi�MN��]9|�UL1j�(�5��w�P��!<�Cc%r0�j!��!�?�"Mٷ��5kb�H��B^~��2��[�n��ƞ1�@���d�ʕr��`>���VBA�H��( ܚ{�AZ6oެ�]FF�K^^5o��`��`4�t���2r
��%�)
Τ3�;rww��ӧSzz�ٺ޸q��N����D�y��<~P�M���Wv1[��m��ؗH[��T�a�Qjj*=~�X������d ׮]#ooo�*w�/�|i6�).� ��;::��������f뗒�Bo��999��lb�q��ܤ�܆B��/�m�اH[�_�ٴii)=��_�R�l�"iCW�T4p�@�r��:���O�� �Y�9(��@�/��)b�"����o��U�+�ݻ7�N�jq9���?~<�n�:����.���k׮E@@�{�=sb��ND��4Ό<
�r���w *�����&F
���e۶m�ϻt�BRPXXHӦM��ի��T�V�>��SJII1����bڹs'լY�ܑ�e]���mf�VBCCeס�ʗ�CE�O�/X�׈�ݻGDD���@���ɢI�gQ�մf��ׯեz��4r�H���(//Ϣ:�?N 64�c�� ��,��&'f�t'�ky���eס�J+Kڢ"�%��Ž6وV�^MZ"##u��]�������)..�֯_O?��-\��8@EEE�}��%z�,�T; �o&f;t� ���8p@vʡ��,m��؏H_ P��!�5��|�ᇺ� D剻w�R�=,�Pw�#��=���ԩS�6"6���<�ow��ER�KE�C����p�Tc��;v�0+N��IOOǨQ�P�V-�ř�ߤ�<p��$T�wb�u��Vg�8::��յL�=^�]� ɍ} &C'ܼyIII�����/���ĦMR�>i�����i�����˗�[��������X4��4]]]u�W������̚�+2�[ i���OG�����}>w�\+�d>��oP�zu̙3GH�C<0@4��VC�x�����U����_�ϪgϞpqq�I]y�9)m;��+��(�e��eE�a̕s��)�߿�Jj�C��`Ŋ�Q��N�jn�6w$`8-�纔0�j�Ǘ.==������Z�E����ԝh������V\8kM8@����eϞ=z���у䤸���m�F����Nr�Ў�<��?BuJMM�&M��=�gSѲz�j�u�qss�K�.�^ ���mV��ӓ=�g�Hc_&''#11 6D۶m������>>>���Enn.��ݍe�G��o�!�A���wD$>X�c~��>)) �j����筨�}QXX'''�+G{ZXe��� 4@�ڵq�Νg�>JDO��K��X��O7�%a�޽hذ!�����g�YQ��uB�V#77��ٸw��L��S�NYZ�f��[�d ���5kJ�����](~��-������ 111ضm��*Ɋ���F�2���FŚ��0�|���ݻo������yyy���Ɠ'O������4<z�)))��>�ܹ��w�"55����ΖlLi�L$���(�bG��ӑ���9���7��1[p��i݄d������6 k׮��},m�w�����Ҏ��{"R3��j,������ ����������l���!99�����۷���#���!##��U1RS�g��ٸ�x�ɐ���矗��B���b�����+�O�ƀ}��A�Z�p��]��*Kdd$6l�3fX��*U�s썜��cD�d�Bš��&��(���������C۷o��>L�4��=*��0*��ᔛ�KZJ�'���oI��P�V��Z�v�z\\��45�LTDz���K-����)��Q2/����n����g�
����BTT��eY�K�.a�ĉ���ѣ,�F��h4P�T�5k�U�iԈ�{���KdU����$���?���$ �����7�b�58;;ӣG���ˋΟ?O���ԴiS��7ݸq�֭['��1)˗/'->4+ �5�믿��ga`=��q�F���L�yU�Q���S��0\�n�����I��!�tpo֩N���
�1��M�:mp#7�݉$����9���K-��;w���ݻiǎ�a�ڸq���'22�rrr�v���������;w��Hq�R�W_}����?��Z=���l*�X�۸��O �Q~�b����d�n�� rw" $��܍��~>� â�^XXH�5��={Rqq�$�&M�D_���z��e��Jw��%-'N�]'�̚5K�׍7�R�J��N�:��L�vn�~ �K�����k��������79T�N$�������ZV�\I , �;L��Ç��rg͚e���nݺ��H:$$��^�JD�!7��T�S>��3Ҳo�>[ן .+��m]�>�@���ր<0 @���5����cl38�X!�U�<�4���p�� 1],�1�@G��x�ԩSX�z5n�ºu�0q�D4i��❵�}����ʜ�{��M���JR��ܼy�۷Ǯ]�ЬY3lذ-[��}cX����nݲu�����(�k�c*�|�����:���>d�}� ���m�ye���q���P�o��(�O���Q��[�jEDD6l��H��ɉ
�Z�X���G��MX�D>��#���oغ�{%mo(������:��,͐�Y����pdl�E>�<�V�'\���%��������˗����7n,w�҉�����DD4}�tYu�:u*X<����%6Of��#w�4���JF�ve��P����X|�~@26�Zf<��� |i�1cYwt߫W/�h4�~�z�;��899��ŋI��Ы��*��'O&"��;wZ\V˖-�nݺb���'-�G �"�ۑ���RgR��wXh�}��A��H.}ݺu�[XX���?�ka�!�_Z�ԩC���V�O�2��F�Z7n=z����e���w�%"�Q�FY\V� ��w(V{s�r?�I*��%�w\�����J�F2Oȍ:t(��˗�����E�;4��ʾ}�Ⱥ�{�d��݀M��U�ڼ��~���� �f+�jբ�'O��WM�>iF~W�6cE)���Znѽ��a��P^6v�U*EEEќ9s�������t��K�8hnuC�4A2r�H""���U*-Y��5j$�5�ڵk�W_}E*�ʦ��?��,Y"�5��,w��[��='�L���x�{3���W@^^^����+V�ÇI˝;w�O>15���?�m�.���!Z<==u�l�Wo޼���lL��ܨe˖6�s̘1�ݓ��0""<x��|���"�o�����up'ϝp �Apa2l�67�}��~`r�ĉٰaCʭ[��4�����P�>}������^NY�f I7��U����T^Dʷ��M��ҥK��k-wl��Vz��ܭ��&�}-�<�T����H�b;)�ܬ{&�C��J��>����ԯ_?�R���_������R��G�!�5UF���$"�Ç�����Pc��D�� ����/h�Aݜ������4�,��~h26w������ѣ��A�@�4!�o��4�E�MZ�j���T)�C�DDt��E1�z��/E�_KV�h��_�Q�z�{K�:O[Ѻ���dh$ �a�rwH;�~%�IED�E�f�֭KǏ��*���!��ƽr劘2��?E��9fܳ�f�-��Q�v��>�:���d����I�T�*}�4h�rbbb�F�1{�L@@=x�@�몰r��1rrr2���ӧ����O?Sf� m �G�����U2����>�V�$�~�� 7|�ܝ�e��# �2�ի��Ȳ���ݻ+��5�K�.DD7����Q^^���)w���Sd_���z��Qn]��{����������e�����v&��<�`[��c���@���G�i���U��∈(**��wӧO'"��>�Hl����?���3Qv��`�xG0�Ӭ�p%�\��-�M��]�6���V��L�>}�7�wpp�nݺ�/��B���F]���ۛbbb��
%���T\\LDd� �3g�Б#G�Y2<[��if�� �����v���q�&�� ������d�`n�orwV;� � �?8���t�1:{�,i4JNN��|��W��R��K'^^^���@DD���԰aC��7nLO�<���0s�_ w��ln�}���b���0�v&���ps���a�@�nU�7����%-iii4o�<���'�FC���r_K�gggڳgq��^z�L� P�~�̭c���2
�7K�f�p���5F��Be��3��2J�!���!�ct��iZ�p!U�V�PLL ���PRR�9��)�1��_��h����P�T�B3f̰����+b7vi��:�Hn�krw\��J�� �1��|֡C��ʢ�+W�}m^�̙C׮]�aÆMS�^=K��5���6����1Z��(� ����� gPj# ��"�R�ݦMJOO��������&�=)7ҥK2d��c4e�����.0��>� F˗�e��Irw`�f�Z��\dN��h޼9]�t�j֬)8O�j�̝DTDZ)��L�nEd�M5�\b��g�l*'��V�dMD}�(��������������������Lj���R �ED#�(Yne"�`�ET5Ux�ѐDe-)�� 4p�~�|��Q ��}�
N߹sg:t����R�믿~��/*b�F���:*��\�`���eծ]��;w���πT��ݚ���Dt�P���>��������B^^oZ���ߏ�={"++˚j)��}��ؾ}{F�*U|��E�0��`p�)���=� ��Ufc���C��R�
���k��曛c�y�
�?�&g�K�--�?+����5p:��g����~<̹Vk1e�ԩS�&M�[�JAPPN�>��3g�����I�ŧ`G0��0ߌ�o��2���"�k� �|U�֭iO��~��-Hp聕�w���jM�V�eggSDD��T$�[�.����}���LG��}��c����.1�gU���>����}A2�L�Pp�72::�v��MD���}�9::��$���\��6@�dժUt��!�"���"�^�U����ĉ4y�d�ϗ,YB�������R�~��<��vЦLYr_�=�>�6�y^z�%��'":s� �nݺt��r_�5�����m��ax��);v���"�d���DD���ruu%��>JD4|���i��.�wW����)G� �'vt]tt��^�z��ѣi�ƍ���IZΝ;G������=���X�Yêr��9z��!���.�c|||�`_���]���]~~>�������S^^m޼����*~}ep��=�$@U�r�;�w�L����t7�`�m�L�[o�EDD�/�V�Z��}�hIDAT�{�ZM������???��>��?��~��ѽ{���͛���LիW6��r�KE�_sB)��W��a�٢Z�j��?�|��/�L]�v�N�'��F��܆�O���(;;�4 -X��������NLL�:Ȯ����@�~�A����ˉ��G��򬒻m*"�7��Șz�d�{p���ft�[r�n�z�E<�~�O�>�h�"�h4DDT\\L?��#���HZ�6�gy�w��^Fׯ_� ��ӓ>��cc����6Տ7��6Z���}�*x�>)����Enc$D���())�J3x�`@�Z���'O�>ONN�A�IVw�V��K�.��s$""����i���N+%F�f)b����S]~�/�^��f�t�/�����H������C���i)�|P�R��o�M��o�^z)!�8;; ��R���ٳT�jU��qww��/R||�9�D��n������|�Ǵy+k 4!���9���:�XL��
!==�z��|���b�+..ƢE�РA���/��ݻ�… �裏P�
���x{{c����޽�.p[qq1�]��E�Y�¬@۶m���#//=z���|c���M�jl�>�1���R٫��e�ÿ�E�| Ln]^�%#�b��]~�j�*�i^|�EJLL$-iii��_�Ӆ �… 4f�rqq� &рd�~c���@����}����˗i�֭���gI�u�n����ǁ?Q�:)ƞ���)uò�
`8��r�fƵ��P����""Z�l��t���4c� �U;���Ըqc�:<==u�URRRt?~�d���f͚$�f��r�MED��#"��Z"R�=�M�`)�W�ȭ��ײSnC%F @DTf˿1 �m۶��իW �+66�RSS�4;w���H���6ݗ?�U�Ǖ ��z��C(3g�ĬY��ݻw ���;�`����h4hР�_�.(_PP�/_�w�Jjj*��������7o��{��-��狾.;�]"Z �
�a���V A��J)b���!�HP��>��_~!"���@�y���k""���+*c����O .�'N�Z�&c�����ȑ#�f��>}:�=J7G�O�Y�����Q�Wc���4h�~~~8t�Z��ɓ�[�.�U�&:/c k׮E�>}P�^=ܻg2ԿQ\\\�֭[�瞃��+�����ꪓ[�na�֭سgOy�$�r+� �ؿ|""�X����H� H4���u��9���E���f�wqq���x�7o��#g{�]r�ME��σE>篕u����*h�Ν���_���"U�z����ϟ7� �Z�޽{�cǎ�^����U8�(�!I"�?����EpaR-fΜ9(**��ŋ�(� 4��=����_�~4h�jUT��V@�,��P��W�H ��ea����ի�|�M)��Ck�/\�`qYIIIصk-.����s�[ qQ
���B�T�}�B2WΝ;w0b�|��w�����XO��s�$)��ի(**���
 �
fqSDZ�b�+�X����0�|lڴ 5k֔��  )) ��钕�`ŕS>�!"-S�}�B����3f )) �7o�l�6 gΜ��,A(���1~{��W2$�@aa! ���0�&lo߾-x竂$(ƾ|��Vq�T2nx"y��na�ȑ5j�z�-��S ��Q�8�1�M�W&�ۍq�e���o���$���q�$�LAYr+�`b��#��W>VY��iӦ!!!�� �7n@��t�e��|"���PzT�c �Lk\PP�����բ ��ׯ+#{ۢ��b��CDy6X��$�=�[�6{���͛�*�`��D�*�
�`�y�?��)�c_9��ъV��_�… ͞�-((���������Q}�D줺2����?X��>��O�6{�V�ی�P0��"�+#�J���յ
j� @^^�Y�����Ⱦ|򪈴��*ƾ�BD|n�:�_���c����_�b�m�b���1���,)ƾr3�_֬`Æ X�t�� ۔�+j�PB:ݔ[ Ѵ �Uy(ƾS��� V]�1y�d�={VԄm�i<
�E�חOƉHKv�����}��YG~~> ���l|��wh߾�5�S���)g0Ƃ ��4=c���~�Ěu\�r�Ǐ���6n�(iH��c 111prr�Uٗ?f�j�P������]h5֬Y�e˖�5a�`"7p��! <�� ��}9�1V�Y
,��ܧ�+b?��|�;�^����ѹs爈觟~�Z=�QZ�nM�oߦS�N�K/�d2���S!G�ۜ"��
@��6��t�� c�=�Y����p�<y�ٳ'���Y]����K�.Ell,��򐜜������j���ʕ+�ȭ��0cS��-����P��BiJ�����5�={6�M��iӦaΜ9֬�R���W^y]�tAhh(�֭����f�!�z
"`���s���Ȗ@D-J�(�V
�""��pp�w��Uϭ[��jղV��G�a�ʕX�r��3www����nݺ�W��߯��:�����貌�*��1�`�zX����W(�1���Z��h�)��v�����ŋ�xQ7? �,��ik�#�{�)�`�������~���Q0���*<x��b�턖�"��f��c��d�)K�d�1��4�LD�g?T���)���5
VF�v�
@'?���1VU^�*'��j6p�u�6X�2A�`��F�@R�����Z "��� ���^_�2�� ��ݕ[��c�\̪(�Y 4&���U����v�Cb�}JJ
jԨ���`ܾ}[ʢ%���/��������@ ���z����q��-�߿���r�.%��`=�[��JɄ�=��� M5�ܛ)`$����@DDm۶�}Cҳ���MC��͛7Snn.�������z�� �]��bcc���]��Pr| �[�6Y��f>���*[�+�d���KU����ѽ{w 86X�X\��T* <C� A׮]��̹K �_B�o�Px�&4ɏ�y�����1��@�� ��p�����.-���_��o�ܣ�*���� I���#���C+��Y�`����ia��
тT,�)� S����uluIP�b�:+�0�
�L @� y��6�${��.� ɽ'9I8����ܜs�o�˽�~g�A�m���ٳgY�t)�ׯ����Ηh%��K��U��ne�"�X�ǥ�cT���N��%s����ǢU�M�TU��g��{����њ������z��4Ƚz��~���l��Z]T���{���aÆ��Z-�\L� �?�mY0e���?�Ic�p�q���3�za]��Z�/�-[Fzz:cǎ�\�N��]R��?�>����ʤ|�ZN���7�ÁX�d .W�Iq�I�9$"͚u�^��_u6EU_k̉��wh��
,�b,��/CBBؼy3+V��&��S��S<� ��9W� 8�����d>]����ػ�F���2Jf/�T� �N��/�o�>z��Y��!C�����̙3|u-�`�����=v+���$����)�L�}q�� �t<�裪��g�[\��ɪ�Z������㪮��0���B=�����B���L���r��v�(�NN�[Ͼ󾪪fffj�>}.�3z�h-,,�4�'�|�#F���M�l���Ym�D���4iN�_�#mS������!::ZUUKKK�{��-j��O����U_~�9�n�g�s#n�ӋWj��"���ʳZ��w���Ҽ^���ϗ(�x���;vL�n����hYY��V]Т�ǵ���/͗��� .Ծ}��m��?����&bzG��Vw4u^'��o|����\ɷ�~K�=���`�ĉ�?�Z%�BDD999Dt�3�a���s���G��7� �ҹ�����쫿���)
�mo��O��<t
�����{��sX\,�_]�k�3�*����߿���L�����̼�k���D����FǗ��>&��.��'M��~�,@Dfb�h��ȑ#���O���䣏>bڴi͞M����� (_���u��G}��#���۹���|յ��~��_�x�4a/�ɳT�^�����I�4�:>�A��Wo���J���8z�(��������R��K`�E�R���"".L7���u�j��T�]�tp��C���:`��׏3�ݻwӥK�x� �̙c�v�9t�#�'��jN�9�a�0���ܛ�C�c��ڵ�s�o����O�{����q�$:�`�Ap��Fmgff���ƞ={HKK#;;�*�!X �^�[��DD�1���
��c����� ���c��Ʋs�N:v��ʕ+IL������s��a�o���i���f)��@/x)7� �j].ԥ3�P[q�i����׀�����=���տZ��֩S�HIIa���<h{�񓘂{��j���Z�q]�%���
`���o@�8���_|��@Nj����?$44���^y啀u���ӧ���Bْ_R������w��G����?[���h�-FP�>�p ���A�K��1w�ۼƃ�r������M�M6j[�
�|�6�����
p�����{��""a�S��@��cO�2��[�L||<[�n�rx���HLL���9��u����M����n�>�Ch�ߏ��C�<a�O l����uL�x�I�j�����Mz�܅�AoE��7CoI�@��;4_E�c6���ea||<��^��x���T������:u*'�܋���:���b�k 5E%xF�QSXlټ�����ͻ��S�~�1�٦�)��_��'Um���|����õ*��]L�vם Z�F!"�0~��4��HIIaΜ9����}�vn��v��>|8�*�Gs�ӊJP�d����TW�q���GUW��P`"&V�:��]� Y#"����M"�<pc��0�U�<U����C�H,&j��S��|�I������'&&����{g�/���;2�:ϛ��g^x�6���s݅����`\=�"Z]�3��
v�jfKM,"0=ag?�����Q`��~nᘗp���U��H�(X�… Y�v-_�5�Ǐ���,��Μ9C����sg�c��hU�����i�?��\���}~�+�Ǭ�wa��U�����qX�p~�Y�71$��8�ޡ"���g�*�|���$%%���ƤI��U]] %�9�k��� ���it]z,���4�V�qȹ���<�˷R�
t���v�q����C60WUw5��c�|��@ �'�����U�V�x�b�m������j�r��z�Ԗ���ݺ}�v@�[=77|Z}D����4ϊ�j����?K}X��{�%Um������A���}��>��^�f���<���$''3o�<�ƨ���s�Pr�7jn�l�8�VO}�V��B`fc����T5�%'m��-�����"�9P�/��6`��ϟϦM��;w���yyyHX(F�X�6M�qܪZ���1�Z�1�g�������-m��1�7"�CD~���#*���������o����W ��<c�Bc�X�^[�����V��j�� � 8�����T�Ov)��v��t��c�Oi���R[[ˬY�ضm7nd���M�>7��ׇ�����a����U�7Uu�&R�FB1�IR�{[b�!c��PY�1�K�N6�d)������פ��flٲ�6::���^�� ��EBZ[�-|�V���v���T�I� �F��`%p��>��;�V�"�m;ėa�p�ݺ4#�U흝�=ʔ)Oeee5�YIqq1AAA��^��7���������VKN("A���٘2m!��z\�$x��i�Ҽ ��1��
�a_%�RL%��X�e��W�:+�E�ŕ����;vl��#G�k�q�w�^bbb��U&�Qq��Y#��í�j����&cJ3DإK)>ĸ�>Vճ6�� ��oLjH4�����L��y�̗,P7O%f�o'&�ส��� @�-��+o�iq�G1M �5f��lٲ���?|�ĉљ��7���-_��^0%������J��J �[=�<����� ��� ���i`?�����Zka�k�� ��R���>׹�(ĸ�R}�z�7��E�E�H��J~��֯^�D-Z׿�؄�������Q��r�X�a�Vxڭ� v+q=D�#0 �,�{3ZG%��|>fQ��m�9[��;����U�)�T���/ik+�?��Yg�� �Զ�Z/���n�<g��""������;Ů��2 �� �R��8�:����dk�1�@�D�^�e�{}�L��s*��n���qh�8����G�DM�T���SUk����H��1L�\� ��b6�u��Utwhyc��p9�x �Ah5��k�z�z����#Q�0+�X��P�[���v��xC';�oc��pr$j�&,0�ʈ��L��[n�4�^y�DEbJ\��l`���+P� u=��[9���s*����wp�9��S�_7b�U��W�RL���m��Z�'����%jEIEND�B`�
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>CodeMirror: Compression Helper</title>
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Droid+Sans|Droid+Sans:bold"/>
<link rel="stylesheet" type="text/css" href="docs.css"/>
</head>
<body>
<h1><span class="logo-braces">{ }</span> <a href="http://codemirror.net/">CodeMirror</a></h1>
<div class="grey">
<img src="baboon.png" class="logo" alt="logo"/>
<pre>
/* Script compression
helper */
</pre>
</div>
<p>To optimize loading CodeMirror, especially when including a
bunch of different modes, it is recommended that you combine and
minify (and preferably also gzip) the scripts. This page makes
those first two steps very easy. Simply select the version and
scripts you need in the form below, and
click <strong>Compress</strong> to download the minified script
file.</p>
<form id="form" action="http://marijnhaverbeke.nl/uglifyjs" method="post">
<input type="hidden" id="download" name="download" value="codemirror-compressed.js"/>
<p>Version: <select id="version" onchange="setVersion(this);" style="padding: 1px">
<option value="http://codemirror.net/">HEAD</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v3.0beta2;f=">3.0beta2</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.35;f=">2.35</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v3.0beta1;f=">3.0beta1</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.34;f=">2.34</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.33;f=">2.33</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.32;f=">2.32</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.31;f=">2.31</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.3;f=">2.3</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.25;f=">2.25</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.24;f=">2.24</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.23;f=">2.23</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.22;f=">2.22</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.21;f=">2.21</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.2;f=">2.2</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.18;f=">2.18</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.16;f=">2.16</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.15;f=">2.15</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.13;f=">2.13</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.12;f=">2.12</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.11;f=">2.11</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.1;f=">2.1</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.02;f=">2.02</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.01;f=">2.01</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.0;f=">2.0</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=beta2;f=">beta2</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=beta1;f=">beta1</option>
</select></p>
<select multiple="multiple" size="20" name="code_url" style="width: 40em;" class="field" id="files">
<optgroup label="CodeMirror Library">
<option value="http://codemirror.net/lib/codemirror.js" selected>codemirror.js</option>
</optgroup>
<optgroup label="Modes">
<option value="http://codemirror.net/mode/clike/clike.js">clike.js</option>
<option value="http://codemirror.net/mode/clojure/clojure.js">clojure.js</option>
<option value="http://codemirror.net/mode/coffeescript/coffeescript.js">coffeescript.js</option>
<option value="http://codemirror.net/mode/commonlisp/commonlisp.js">commonlisp.js</option>
<option value="http://codemirror.net/mode/css/css.js">css.js</option>
<option value="http://codemirror.net/mode/diff/diff.js">diff.js</option>
<option value="http://codemirror.net/mode/ecl/ecl.js">ecl.js</option>
<option value="http://codemirror.net/mode/erlang/erlang.js">erlang.js</option>
<option value="http://codemirror.net/mode/gfm/gfm.js">gfm.js</option>
<option value="http://codemirror.net/mode/go/go.js">go.js</option>
<option value="http://codemirror.net/mode/groovy/groovy.js">groovy.js</option>
<option value="http://codemirror.net/mode/haskell/haskell.js">haskell.js</option>
<option value="http://codemirror.net/mode/haxe/haxe.js">haxe.js</option>
<option value="http://codemirror.net/mode/htmlembedded/htmlembedded.js">htmlembedded.js</option>
<option value="http://codemirror.net/mode/htmlmixed/htmlmixed.js">htmlmixed.js</option>
<option value="http://codemirror.net/mode/javascript/javascript.js">javascript.js</option>
<option value="http://codemirror.net/mode/jinja2/jinja2.js">jinja2.js</option>
<option value="http://codemirror.net/mode/less/less.js">less.js</option>
<option value="http://codemirror.net/mode/lua/lua.js">lua.js</option>
<option value="http://codemirror.net/mode/markdown/markdown.js">markdown.js</option>
<option value="http://codemirror.net/mode/mysql/mysql.js">mysql.js</option>
<option value="http://codemirror.net/mode/ntriples/ntriples.js">ntriples.js</option>
<option value="http://codemirror.net/mode/ocaml/ocaml.js">ocaml.js</option>
<option value="http://codemirror.net/mode/pascal/pascal.js">pascal.js</option>
<option value="http://codemirror.net/mode/perl/perl.js">perl.js</option>
<option value="http://codemirror.net/mode/php/php.js">php.js</option>
<option value="http://codemirror.net/mode/pig/pig.js">pig.js</option>
<option value="http://codemirror.net/mode/plsql/plsql.js">plsql.js</option>
<option value="http://codemirror.net/mode/properties/properties.js">properties.js</option>
<option value="http://codemirror.net/mode/python/python.js">python.js</option>
<option value="http://codemirror.net/mode/r/r.js">r.js</option>
<option value="http://codemirror.net/mode/rpm/changes/changes.js">rpm/changes.js</option>
<option value="http://codemirror.net/mode/rpm/spec/spec.js">rpm/spec.js</option>
<option value="http://codemirror.net/mode/rst/rst.js">rst.js</option>
<option value="http://codemirror.net/mode/ruby/ruby.js">ruby.js</option>
<option value="http://codemirror.net/mode/rust/rust.js">rust.js</option>
<option value="http://codemirror.net/mode/scheme/scheme.js">scheme.js</option>
<option value="http://codemirror.net/mode/shell/shell.js">shell.js</option>
<option value="http://codemirror.net/mode/sieve/sieve.js">sieve.js</option>
<option value="http://codemirror.net/mode/smalltalk/smalltalk.js">smalltalk.js</option>
<option value="http://codemirror.net/mode/smarty/smarty.js">smarty.js</option>
<option value="http://codemirror.net/mode/sparql/sparql.js">sparql.js</option>
<option value="http://codemirror.net/mode/stex/stex.js">stex.js</option>
<option value="http://codemirror.net/mode/tiddlywiki/tiddlywiki.js">tiddlywiki.js</option>
<option value="http://codemirror.net/mode/tiki/tiki.js">tiki.js</option>
<option value="http://codemirror.net/mode/vb/vb.js">vb.js</option>
<option value="http://codemirror.net/mode/vbscript/vbscript.js">vbscript.js</option>
<option value="http://codemirror.net/mode/velocity/velocity.js">velocity.js</option>
<option value="http://codemirror.net/mode/verilog/verilog.js">verilog.js</option>
<option value="http://codemirror.net/mode/xml/xml.js">xml.js</option>
<option value="http://codemirror.net/mode/xquery/xquery.js">xquery.js</option>
<option value="http://codemirror.net/mode/yaml/yaml.js">yaml.js</option>
</optgroup>
<optgroup label="Utilities and add-ons">
<option value="http://codemirror.net/lib/util/overlay.js">overlay.js</option>
<option value="http://codemirror.net/lib/util/multiplex.js">multiplex.js</option>
<option value="http://codemirror.net/lib/util/runmode.js">runmode.js</option>
<option value="http://codemirror.net/lib/util/simple-hint.js">simple-hint.js</option>
<option value="http://codemirror.net/lib/util/javascript-hint.js">javascript-hint.js</option>
<option value="http://codemirror.net/lib/util/xml-hint.js">xml-hint.js</option>
<option value="http://codemirror.net/lib/util/foldcode.js">foldcode.js</option>
<option value="http://codemirror.net/lib/util/dialog.js">dialog.js</option>
<option value="http://codemirror.net/lib/util/search.js">search.js</option>
<option value="http://codemirror.net/lib/util/searchcursor.js">searchcursor.js</option>
<option value="http://codemirror.net/lib/util/formatting.js">formatting.js</option>
<option value="http://codemirror.net/lib/util/match-highlighter.js">match-highlighter.js</option>
<option value="http://codemirror.net/lib/util/closetag.js">closetag.js</option>
<option value="http://codemirror.net/lib/util/loadmode.js">loadmode.js</option>
</optgroup>
<optgroup label="Keymaps">
<option value="http://codemirror.net/keymap/emacs.js">emacs.js</option>
<option value="http://codemirror.net/keymap/vim.js">vim.js</option>
</optgroup>
</select></p>
<p>
<button type="submit">Compress</button> with <a href="http://github.com/mishoo/UglifyJS/">UglifyJS</a>
</p>
<p>Custom code to add to the compressed file:<textarea name="js_code" style="width: 100%; height: 15em;" class="field"></textarea></p>
</form>
<script type="text/javascript">
function setVersion(ver) {
var urlprefix = ver.options[ver.selectedIndex].value;
var select = document.getElementById("files"), m;
for (var optgr = select.firstChild; optgr; optgr = optgr.nextSibling)
for (var opt = optgr.firstChild; opt; opt = opt.nextSibling) {
if (opt.nodeName != "OPTION")
continue;
else if (m = opt.value.match(/^http:\/\/codemirror.net\/(.*)$/))
opt.value = urlprefix + m[1];
else if (m = opt.value.match(/http:\/\/marijnhaverbeke.nl\/git\/codemirror\?a=blob_plain;hb=[^;]+;f=(.*)$/))
opt.value = urlprefix + m[1];
}
}
</script>
</body>
</html>
body {
font-family: Droid Sans, Arial, sans-serif;
line-height: 1.5;
max-width: 64.3em;
margin: 3em auto;
padding: 0 1em;
}
h1 {
letter-spacing: -3px;
font-size: 3.23em;
font-weight: bold;
margin: 0;
}
h2 {
font-size: 1.23em;
font-weight: bold;
margin: .5em 0;
letter-spacing: -1px;
}
h3 {
font-size: 1em;
font-weight: bold;
margin: .4em 0;
}
pre {
background-color: #eee;
-moz-border-radius: 6px;
-webkit-border-radius: 6px;
border-radius: 6px;
padding: 1em;
}
pre.code {
margin: 0 1em;
}
.grey {
background-color: #eee;
border-radius: 6px;
margin-bottom: 1.65em;
margin-top: 0.825em;
padding: 0.825em 1.65em;
position: relative;
}
img.logo {
position: absolute;
right: -1em;
bottom: 4px;
max-width: 23.6875em; /* Scale image down with text to prevent clipping */
}
.grey > pre {
background:none;
border-radius:0;
padding:0;
margin:0;
font-size:2.2em;
line-height:1.2em;
}
a:link, a:visited, .quasilink {
color: #df0019;
cursor: pointer;
text-decoration: none;
}
a:hover, .quasilink:hover {
color: #800004;
}
h1 a:link, h1 a:visited, h1 a:hover {
color: black;
}
ul {
margin: 0;
padding-left: 1.2em;
}
a.download {
color: white;
background-color: #df0019;
width: 100%;
display: block;
text-align: center;
font-size: 1.23em;
font-weight: bold;
text-decoration: none;
-moz-border-radius: 6px;
-webkit-border-radius: 6px;
border-radius: 6px;
padding: .5em 0;
margin-bottom: 1em;
}
a.download:hover {
background-color: #bb0010;
}
.rel {
margin-bottom: 0;
}
.rel-note {
color: #777;
font-size: .9em;
margin-top: .1em;
}
.logo-braces {
color: #df0019;
position: relative;
top: -4px;
}
.blk {
float: left;
}
.left {
width: 37em;
padding-right: 6.53em;
padding-bottom: 1em;
}
.left1 {
width: 15.24em;
padding-right: 6.45em;
}
.left2 {
width: 15.24em;
}
.right {
width: 20.68em;
}
.leftbig {
width: 42.44em;
padding-right: 6.53em;
}
.rightsmall {
width: 15.24em;
}
.clear:after {
visibility: hidden;
display: block;
font-size: 0;
content: " ";
clear: both;
height: 0;
}
.clear { display: inline-block; }
/* start commented backslash hack \*/
* html .clear { height: 1%; }
.clear { display: block; }
/* close commented backslash hack */
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>CodeMirror: Internals</title>
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Droid+Sans|Droid+Sans:bold"/>
<link rel="stylesheet" type="text/css" href="docs.css"/>
<style>dl dl {margin: 0;} .update {color: #d40 !important}</style>
</head>
<body>
<h1><span class="logo-braces">{ }</span> <a href="http://codemirror.net/">CodeMirror</a></h1>
<div class="grey">
<img src="baboon.png" class="logo" alt="logo"/>
<pre>
/* (Re-) Implementing A Syntax-
Highlighting Editor in JavaScript */
</pre>
</div>
<div class="clear"><div class="leftbig blk">
<p style="font-size: 85%" id="intro">
<strong>Topic:</strong> JavaScript, code editor implementation<br>
<strong>Author:</strong> Marijn Haverbeke<br>
<strong>Date:</strong> March 2nd 2011 (updated November 13th 2011)
</p>
<p>This is a followup to
my <a href="http://codemirror.net/story.html">Brutal Odyssey to the
Dark Side of the DOM Tree</a> story. That one describes the
mind-bending process of implementing (what would become) CodeMirror 1.
This one describes the internals of CodeMirror 2, a complete rewrite
and rethink of the old code base. I wanted to give this piece another
Hunter Thompson copycat subtitle, but somehow that would be out of
place—the process this time around was one of straightforward
engineering, requiring no serious mind-bending whatsoever.</p>
<p>So, what is wrong with CodeMirror 1? I'd estimate, by mailing list
activity and general search-engine presence, that it has been
integrated into about a thousand systems by now. The most prominent
one, since a few weeks,
being <a href="http://googlecode.blogspot.com/2011/01/make-quick-fixes-quicker-on-google.html">Google
code's project hosting</a>. It works, and it's being used widely.</a>
<p>Still, I did not start replacing it because I was bored. CodeMirror
1 was heavily reliant on <code>designMode</code>
or <code>contentEditable</code> (depending on the browser). Neither of
these are well specified (HTML5 tries
to <a href="http://www.w3.org/TR/html5/editing.html#contenteditable">specify</a>
their basics), and, more importantly, they tend to be one of the more
obscure and buggy areas of browser functionality—CodeMirror, by using
this functionality in a non-typical way, was constantly running up
against browser bugs. WebKit wouldn't show an empty line at the end of
the document, and in some releases would suddenly get unbearably slow.
Firefox would show the cursor in the wrong place. Internet Explorer
would insist on linkifying everything that looked like a URL or email
address, a behaviour that can't be turned off. Some bugs I managed to
work around (which was often a frustrating, painful process), others,
such as the Firefox cursor placement, I gave up on, and had to tell
user after user that they were known problems, but not something I
could help.</p>
<p>Also, there is the fact that <code>designMode</code> (which seemed
to be less buggy than <code>contentEditable</code> in Webkit and
Firefox, and was thus used by CodeMirror 1 in those browsers) requires
a frame. Frames are another tricky area. It takes some effort to
prevent getting tripped up by domain restrictions, they don't
initialize synchronously, behave strangely in response to the back
button, and, on several browsers, can't be moved around the DOM
without having them re-initialize. They did provide a very nice way to
namespace the library, though—CodeMirror 1 could freely pollute the
namespace inside the frame.</p>
<p>Finally, working with an editable document means working with
selection in arbitrary DOM structures. Internet Explorer (8 and
before) has an utterly different (and awkward) selection API than all
of the other browsers, and even among the different implementations of
<code>document.selection</code>, details about how exactly a selection
is represented vary quite a bit. Add to that the fact that Opera's
selection support tended to be very buggy until recently, and you can
imagine why CodeMirror 1 contains 700 lines of selection-handling
code.</p>
<p>And that brings us to the main issue with the CodeMirror 1
code base: The proportion of browser-bug-workarounds to real
application code was getting dangerously high. By building on top of a
few dodgy features, I put the system in a vulnerable position—any
incompatibility and bugginess in these features, I had to paper over
with my own code. Not only did I have to do some serious stunt-work to
get it to work on older browsers (as detailed in the
previous <a href="http://codemirror.net/story.html">story</a>), things
also kept breaking in newly released versions, requiring me to come up
with <em>new</em> scary hacks in order to keep up. This was starting
to lose its appeal.</p>
<h2 id="approach">General Approach</h2>
<p>What CodeMirror 2 does is try to sidestep most of the hairy hacks
that came up in version 1. I owe a lot to the
<a href="http://ace.ajax.org">ACE</a> editor for inspiration on how to
approach this.</p>
<p>I absolutely did not want to be completely reliant on key events to
generate my input. Every JavaScript programmer knows that key event
information is horrible and incomplete. Some people (most awesomely
Mihai Bazon with <a href="http://ymacs.org">Ymacs</a>) have been able
to build more or less functioning editors by directly reading key
events, but it takes a lot of work (the kind of never-ending, fragile
work I described earlier), and will never be able to properly support
things like multi-keystoke international character
input. <a href="#keymap" class="update">[see below for caveat]</a></p>
<p>So what I do is focus a hidden textarea, and let the browser
believe that the user is typing into that. What we show to the user is
a DOM structure we built to represent his document. If this is updated
quickly enough, and shows some kind of believable cursor, it feels
like a real text-input control.</p>
<p>Another big win is that this DOM representation does not have to
span the whole document. Some CodeMirror 1 users insisted that they
needed to put a 30 thousand line XML document into CodeMirror. Putting
all that into the DOM takes a while, especially since, for some
reason, an editable DOM tree is slower than a normal one on most
browsers. If we have full control over what we show, we must only
ensure that the visible part of the document has been added, and can
do the rest only when needed. (Fortunately, the <code>onscroll</code>
event works almost the same on all browsers, and lends itself well to
displaying things only as they are scrolled into view.)</p>
<h2 id="input">Input</h2>
<p>ACE uses its hidden textarea only as a text input shim, and does
all cursor movement and things like text deletion itself by directly
handling key events. CodeMirror's way is to let the browser do its
thing as much as possible, and not, for example, define its own set of
key bindings. One way to do this would have been to have the whole
document inside the hidden textarea, and after each key event update
the display DOM to reflect what's in that textarea.</p>
<p>That'd be simple, but it is not realistic. For even medium-sized
document the editor would be constantly munging huge strings, and get
terribly slow. What CodeMirror 2 does is put the current selection,
along with an extra line on the top and on the bottom, into the
textarea.</p>
<p>This means that the arrow keys (and their ctrl-variations), home,
end, etcetera, do not have to be handled specially. We just read the
cursor position in the textarea, and update our cursor to match it.
Also, copy and paste work pretty much for free, and people get their
native key bindings, without any special work on my part. For example,
I have emacs key bindings configured for Chrome and Firefox. There is
no way for a script to detect this. <a class="update"
href="#keymap">[no longer the case]</a></p>
<p>Of course, since only a small part of the document sits in the
textarea, keys like page up and ctrl-end won't do the right thing.
CodeMirror is catching those events and handling them itself.</p>
<h2 id="selection">Selection</h2>
<p>Getting and setting the selection range of a textarea in modern
browsers is trivial—you just use the <code>selectionStart</code>
and <code>selectionEnd</code> properties. On IE you have to do some
insane stuff with temporary ranges and compensating for the fact that
moving the selection by a 'character' will treat \r\n as a single
character, but even there it is possible to build functions that
reliably set and get the selection range.</p>
<p>But consider this typical case: When I'm somewhere in my document,
press shift, and press the up arrow, something gets selected. Then, if
I, still holding shift, press the up arrow again, the top of my
selection is adjusted. The selection remembers where its <em>head</em>
and its <em>anchor</em> are, and moves the head when we shift-move.
This is a generally accepted property of selections, and done right by
every editing component built in the past twenty years.</p>
<p>But not something that the browser selection APIs expose.</p>
<p>Great. So when someone creates an 'upside-down' selection, the next
time CodeMirror has to update the textarea, it'll re-create the
selection as an 'upside-up' selection, with the anchor at the top, and
the next cursor motion will behave in an unexpected way—our second
up-arrow press in the example above will not do anything, since it is
interpreted in exactly the same way as the first.</p>
<p>No problem. We'll just, ehm, detect that the selection is
upside-down (you can tell by the way it was created), and then, when
an upside-down selection is present, and a cursor-moving key is
pressed in combination with shift, we quickly collapse the selection
in the textarea to its start, allow the key to take effect, and then
combine its new head with its old anchor to get the <em>real</em>
selection.</p>
<p>In short, scary hacks could not be avoided entirely in CodeMirror
2.</p>
<p>And, the observant reader might ask, how do you even know that a
key combo is a cursor-moving combo, if you claim you support any
native key bindings? Well, we don't, but we can learn. The editor
keeps a set known cursor-movement combos (initialized to the
predictable defaults), and updates this set when it observes that
pressing a certain key had (only) the effect of moving the cursor.
This, of course, doesn't work if the first time the key is used was
for extending an inverted selection, but it works most of the
time.</p>
<h2 id="update">Intelligent Updating</h2>
<p>One thing that always comes up when you have a complicated internal
state that's reflected in some user-visible external representation
(in this case, the displayed code and the textarea's content) is
keeping the two in sync. The naive way is to just update the display
every time you change your state, but this is not only error prone
(you'll forget), it also easily leads to duplicate work on big,
composite operations. Then you start passing around flags indicating
whether the display should be updated in an attempt to be efficient
again and, well, at that point you might as well give up completely.</p>
<p>I did go down that road, but then switched to a much simpler model:
simply keep track of all the things that have been changed during an
action, and then, only at the end, use this information to update the
user-visible display.</p>
<p>CodeMirror uses a concept of <em>operations</em>, which start by
calling a specific set-up function that clears the state and end by
calling another function that reads this state and does the required
updating. Most event handlers, and all the user-visible methods that
change state are wrapped like this. There's a method
called <code>operation</code> that accepts a function, and returns
another function that wraps the given function as an operation.</p>
<p>It's trivial to extend this (as CodeMirror does) to detect nesting,
and, when an operation is started inside an operation, simply
increment the nesting count, and only do the updating when this count
reaches zero again.</p>
<p>If we have a set of changed ranges and know the currently shown
range, we can (with some awkward code to deal with the fact that
changes can add and remove lines, so we're dealing with a changing
coordinate system) construct a map of the ranges that were left
intact. We can then compare this map with the part of the document
that's currently visible (based on scroll offset and editor height) to
determine whether something needs to be updated.</p>
<p>CodeMirror uses two update algorithms—a full refresh, where it just
discards the whole part of the DOM that contains the edited text and
rebuilds it, and a patch algorithm, where it uses the information
about changed and intact ranges to update only the out-of-date parts
of the DOM. When more than 30 percent (which is the current heuristic,
might change) of the lines need to be updated, the full refresh is
chosen (since it's faster to do than painstakingly finding and
updating all the changed lines), in the other case it does the
patching (so that, if you scroll a line or select another character,
the whole screen doesn't have to be
re-rendered). <span class="update">[the full-refresh
algorithm was dropped, it wasn't really faster than the patching
one]</span></p>
<p>All updating uses <code>innerHTML</code> rather than direct DOM
manipulation, since that still seems to be by far the fastest way to
build documents. There's a per-line function that combines the
highlighting, <a href="manual.html#markText">marking</a>, and
selection info for that line into a snippet of HTML. The patch updater
uses this to reset individual lines, the refresh updater builds an
HTML chunk for the whole visible document at once, and then uses a
single <code>innerHTML</code> update to do the refresh.</p>
<h2 id="parse">Parsers can be Simple</h2>
<p>When I wrote CodeMirror 1, I
thought <a href="http://codemirror.net/story.html#parser">interruptable
parsers</a> were a hugely scary and complicated thing, and I used a
bunch of heavyweight abstractions to keep this supposed complexity
under control: parsers
were <a href="http://bob.pythonmac.org/archives/2005/07/06/iteration-in-javascript/">iterators</a>
that consumed input from another iterator, and used funny
closure-resetting tricks to copy and resume themselves.</p>
<p>This made for a rather nice system, in that parsers formed strictly
separate modules, and could be composed in predictable ways.
Unfortunately, it was quite slow (stacking three or four iterators on
top of each other), and extremely intimidating to people not used to a
functional programming style.</p>
<p>With a few small changes, however, we can keep all those
advantages, but simplify the API and make the whole thing less
indirect and inefficient. CodeMirror
2's <a href="manual.html#modeapi">mode API</a> uses explicit state
objects, and makes the parser/tokenizer a function that simply takes a
state and a character stream abstraction, advances the stream one
token, and returns the way the token should be styled. This state may
be copied, optionally in a mode-defined way, in order to be able to
continue a parse at a given point. Even someone who's never touched a
lambda in his life can understand this approach. Additionally, far
fewer objects are allocated in the course of parsing now.</p>
<p>The biggest speedup comes from the fact that the parsing no longer
has to touch the DOM though. In CodeMirror 1, on an older browser, you
could <em>see</em> the parser work its way through the document,
managing some twenty lines in each 50-millisecond time slice it got. It
was reading its input from the DOM, and updating the DOM as it went
along, which any experienced JavaScript programmer will immediately
spot as a recipe for slowness. In CodeMirror 2, the parser usually
finishes the whole document in a single 100-millisecond time slice—it
manages some 1500 lines during that time on Chrome. All it has to do
is munge strings, so there is no real reason for it to be slow
anymore.</p>
<h2 id="summary">What Gives?</h2>
<p>Given all this, what can you expect from CodeMirror 2?</p>
<ul>
<li><strong>Small.</strong> the base library is
some <span class="update">45k</span> when minified
now, <span class="update">17k</span> when gzipped. It's smaller than
its own logo.</li>
<li><strong>Lightweight.</strong> CodeMirror 2 initializes very
quickly, and does almost no work when it is not focused. This means
you can treat it almost like a textarea, have multiple instances on a
page without trouble.</li>
<li><strong>Huge document support.</strong> Since highlighting is
really fast, and no DOM structure is being built for non-visible
content, you don't have to worry about locking up your browser when a
user enters a megabyte-sized document.</li>
<li><strong>Extended API.</strong> Some things kept coming up in the
mailing list, such as marking pieces of text or lines, which were
extremely hard to do with CodeMirror 1. The new version has proper
support for these built in.</li>
<li><strong>Tab support.</strong> Tabs inside editable documents were,
for some reason, a no-go. At least six different people announced they
were going to add tab support to CodeMirror 1, none survived (I mean,
none delivered a working version). CodeMirror 2 no longer removes tabs
from your document.</li>
<li><strong>Sane styling.</strong> <code>iframe</code> nodes aren't
really known for respecting document flow. Now that an editor instance
is a plain <code>div</code> element, it is much easier to size it to
fit the surrounding elements. You don't even have to make it scroll if
you do not <a href="../demo/resize.html">want to</a>.</li>
</ul>
<p>On the downside, a CodeMirror 2 instance is <em>not</em> a native
editable component. Though it does its best to emulate such a
component as much as possible, there is functionality that browsers
just do not allow us to hook into. Doing select-all from the context
menu, for example, is not currently detected by CodeMirror.</p>
<p id="changes" style="margin-top: 2em;"><span style="font-weight:
bold">[Updates from November 13th 2011]</span> Recently, I've made
some changes to the codebase that cause some of the text above to no
longer be current. I've left the text intact, but added markers at the
passages that are now inaccurate. The new situation is described
below.</p>
<h2 id="btree">Content Representation</h2>
<p>The original implementation of CodeMirror 2 represented the
document as a flat array of line objects. This worked well—splicing
arrays will require the part of the array after the splice to be
moved, but this is basically just a simple <code>memmove</code> of a
bunch of pointers, so it is cheap even for huge documents.</p>
<p>However, I recently added line wrapping and code folding (line
collapsing, basically). Once lines start taking up a non-constant
amount of vertical space, looking up a line by vertical position
(which is needed when someone clicks the document, and to determine
the visible part of the document during scrolling) can only be done
with a linear scan through the whole array, summing up line heights as
you go. Seeing how I've been going out of my way to make big documents
fast, this is not acceptable.</p>
<p>The new representation is based on a B-tree. The leaves of the tree
contain arrays of line objects, with a fixed minimum and maximum size,
and the non-leaf nodes simply hold arrays of child nodes. Each node
stores both the amount of lines that live below them and the vertical
space taken up by these lines. This allows the tree to be indexed both
by line number and by vertical position, and all access has
logarithmic complexity in relation to the document size.</p>
<p>I gave line objects and tree nodes parent pointers, to the node
above them. When a line has to update its height, it can simply walk
these pointers to the top of the tree, adding or subtracting the
difference in height from each node it encounters. The parent pointers
also make it cheaper (in complexity terms, the difference is probably
tiny in normal-sized documents) to find the current line number when
given a line object. In the old approach, the whole document array had
to be searched. Now, we can just walk up the tree and count the sizes
of the nodes coming before us at each level.</p>
<p>I chose B-trees, not regular binary trees, mostly because they
allow for very fast bulk insertions and deletions. When there is a big
change to a document, it typically involves adding, deleting, or
replacing a chunk of subsequent lines. In a regular balanced tree, all
these inserts or deletes would have to be done separately, which could
be really expensive. In a B-tree, to insert a chunk, you just walk
down the tree once to find where it should go, insert them all in one
shot, and then break up the node if needed. This breaking up might
involve breaking up nodes further up, but only requires a single pass
back up the tree. For deletion, I'm somewhat lax in keeping things
balanced—I just collapse nodes into a leaf when their child count goes
below a given number. This means that there are some weird editing
patterns that may result in a seriously unbalanced tree, but even such
an unbalanced tree will perform well, unless you spend a day making
strangely repeating edits to a really big document.</p>
<h2 id="keymap">Keymaps</h2>
<p><a href="#approach">Above</a>, I claimed that directly catching key
events for things like cursor movement is impractical because it
requires some browser-specific kludges. I then proceeded to explain
some awful <a href="#selection">hacks</a> that were needed to make it
possible for the selection changes to be detected through the
textarea. In fact, the second hack is about as bad as the first.</p>
<p>On top of that, in the presence of user-configurable tab sizes and
collapsed and wrapped lines, lining up cursor movement in the textarea
with what's visible on the screen becomes a nightmare. Thus, I've
decided to move to a model where the textarea's selection is no longer
depended on.</p>
<p>So I moved to a model where all cursor movement is handled by my
own code. This adds support for a goal column, proper interaction of
cursor movement with collapsed lines, and makes it possible for
vertical movement to move through wrapped lines properly, instead of
just treating them like non-wrapped lines.</p>
<p>The key event handlers now translate the key event into a string,
something like <code>Ctrl-Home</code> or <code>Shift-Cmd-R</code>, and
use that string to look up an action to perform. To make keybinding
customizable, this lookup goes through
a <a href="manual.html#option_keyMap">table</a>, using a scheme that
allows such tables to be chained together (for example, the default
Mac bindings fall through to a table named 'emacsy', which defines
basic Emacs-style bindings like <code>Ctrl-F</code>, and which is also
used by the custom Emacs bindings).</p>
<p>A new
option <a href="manual.html#option_extraKeys"><code>extraKeys</code></a>
allows ad-hoc keybindings to be defined in a much nicer way than what
was possible with the
old <a href="manual.html#option_onKeyEvent"><code>onKeyEvent</code></a>
callback. You simply provide an object mapping key identifiers to
functions, instead of painstakingly looking at raw key events.</p>
<p>Built-in commands map to strings, rather than functions, for
example <code>"goLineUp"</code> is the default action bound to the up
arrow key. This allows new keymaps to refer to them without
duplicating any code. New commands can be defined by assigning to
the <code>CodeMirror.commands</code> object, which maps such commands
to functions.</p>
<p>The hidden textarea now only holds the current selection, with no
extra characters around it. This has a nice advantage: polling for
input becomes much, much faster. If there's a big selection, this text
does not have to be read from the textarea every time—when we poll,
just noticing that something is still selected is enough to tell us
that no new text was typed.</p>
<p>The reason that cheap polling is important is that many browsers do
not fire useful events on IME (input method engine) input, which is
the thing where people inputting a language like Japanese or Chinese
use multiple keystrokes to create a character or sequence of
characters. Most modern browsers fire <code>input</code> when the
composing is finished, but many don't fire anything when the character
is updated <em>during</em> composition. So we poll, whenever the
editor is focused, to provide immediate updates of the display.</p>
</div><div class="rightsmall blk">
<h2>Contents</h2>
<ul>
<li><a href="#intro">Introduction</a></li>
<li><a href="#approach">General Approach</a></li>
<li><a href="#input">Input</a></li>
<li><a href="#selection">Selection</a></li>
<li><a href="#update">Intelligent Updating</a></li>
<li><a href="#parse">Parsing</a></li>
<li><a href="#summary">What Gives?</a></li>
<li><a href="#btree">Content Representation</a></li>
<li><a href="#keymap">Key Maps</a></li>
</ul>
</div></div>
<div style="height: 2em">&nbsp;</div>
</body></html>
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>CodeMirror: User Manual</title>
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Droid+Sans|Droid+Sans:bold"/>
<link rel="stylesheet" type="text/css" href="docs.css"/>
<style>dl dl {margin: 0;}</style>
</head>
<body>
<h1><span class="logo-braces">{ }</span> <a href="http://codemirror.net/">CodeMirror</a></h1>
<div class="grey">
<img src="baboon.png" class="logo" alt="logo"/>
<pre>
/* User manual and
reference guide */
</pre>
</div>
<div class="clear"><div class="leftbig blk">
<h2 id="overview">Overview</h2>
<p>CodeMirror is a code-editor component that can be embedded in
Web pages. The code library provides <em>only</em> the editor
component, no accompanying buttons, auto-completion, or other IDE
functionality. It does provide a rich API on top of which such
functionality can be straightforwardly implemented. See
the <a href="#addons">add-ons</a> included in the distribution,
and
the <a href="https://github.com/jagthedrummer/codemirror-ui">CodeMirror
UI</a> project, for reusable implementations of extra features.</p>
<p>CodeMirror works with language-specific modes. Modes are
JavaScript programs that help color (and optionally indent) text
written in a given language. The distribution comes with a number
of modes (see the <code>mode/</code> directory), and it isn't hard
to <a href="#modeapi">write new ones</a> for other languages.</p>
<h2 id="usage">Basic Usage</h2>
<p>The easiest way to use CodeMirror is to simply load the script
and style sheet found under <code>lib/</code> in the distribution,
plus a mode script from one of the <code>mode/</code> directories
and a theme stylesheet from <code>theme/</code>. (See
also <a href="compress.html">the compression helper</a>.) For
example:</p>
<pre>&lt;script src="lib/codemirror.js">&lt;/script>
&lt;link rel="stylesheet" href="../lib/codemirror.css">
&lt;script src="mode/javascript/javascript.js">&lt;/script></pre>
<p>Having done this, an editor instance can be created like
this:</p>
<pre>var myCodeMirror = CodeMirror(document.body);</pre>
<p>The editor will be appended to the document body, will start
empty, and will use the mode that we loaded. To have more control
over the new editor, a configuration object can be passed
to <code>CodeMirror</code> as a second argument:</p>
<pre>var myCodeMirror = CodeMirror(document.body, {
value: "function myScript(){return 100;}\n",
mode: "javascript"
});</pre>
<p>This will initialize the editor with a piece of code already in
it, and explicitly tell it to use the JavaScript mode (which is
useful when multiple modes are loaded).
See <a href="#config">below</a> for a full discussion of the
configuration options that CodeMirror accepts.</p>
<p>In cases where you don't want to append the editor to an
element, and need more control over the way it is inserted, the
first argument to the <code>CodeMirror</code> function can also
be a function that, when given a DOM element, inserts it into the
document somewhere. This could be used to, for example, replace a
textarea with a real editor:</p>
<pre>var myCodeMirror = CodeMirror(function(elt) {
myTextArea.parentNode.replaceChild(elt, myTextArea);
}, {value: myTextArea.value});</pre>
<p>However, for this use case, which is a common way to use
CodeMirror, the library provides a much more powerful
shortcut:</p>
<pre>var myCodeMirror = CodeMirror.fromTextArea(myTextArea);</pre>
<p>This will, among other things, ensure that the textarea's value
is updated when the form (if it is part of a form) is submitted.
See the <a href="#fromTextArea">API reference</a> for a full
description of this method.</p>
<h2 id="config">Configuration</h2>
<p>Both the <code>CodeMirror</code> function and
its <code>fromTextArea</code> method take as second (optional)
argument an object containing configuration options. Any option
not supplied like this will be taken
from <code>CodeMirror.defaults</code>, an object containing the
default options. You can update this object to change the defaults
on your page.</p>
<p>Options are not checked in any way, so setting bogus option
values is bound to lead to odd errors.</p>
<p>These are the supported options:</p>
<dl>
<dt id="option_value"><code>value (string)</code></dt>
<dd>The starting value of the editor.</dd>
<dt id="option_mode"><code>mode (string or object)</code></dt>
<dd>The mode to use. When not given, this will default to the
first mode that was loaded. It may be a string, which either
simply names the mode or is
a <a href="http://en.wikipedia.org/wiki/MIME">MIME</a> type
associated with the mode. Alternatively, it may be an object
containing configuration options for the mode, with
a <code>name</code> property that names the mode (for
example <code>{name: "javascript", json: true}</code>). The demo
pages for each mode contain information about what configuration
parameters the mode supports. You can ask CodeMirror which modes
and MIME types are loaded with
the <code>CodeMirror.listModes</code>
and <code>CodeMirror.listMIMEs</code> functions.</dd>
<dt id="option_theme"><code>theme (string)</code></dt>
<dd>The theme to style the editor with. You must make sure the
CSS file defining the corresponding <code>.cm-s-[name]</code>
styles is loaded (see
the <a href="../theme/"><code>theme</code></a> directory in the
distribution). The default is <code>"default"</code>, for which
colors are included in <code>codemirror.css</code>. It is
possible to use multiple theming classes at once—for
example <code>"foo bar"</code> will assign both
the <code>cm-s-foo</code> and the <code>cm-s-bar</code> classes
to the editor.</dd>
<dt id="option_indentUnit"><code>indentUnit (integer)</code></dt>
<dd>How many spaces a block (whatever that means in the edited
language) should be indented. The default is 2.</dd>
<dt id="option_smartIndent"><code>smartIndent (boolean)</code></dt>
<dd>Whether to use the context-sensitive indentation that the
mode provides (or just indent the same as the line before).
Defaults to true.</dd>
<dt id="option_tabSize"><code>tabSize (integer)</code></dt>
<dd>The width of a tab character. Defaults to 4.</dd>
<dt id="option_indentWithTabs"><code>indentWithTabs (boolean)</code></dt>
<dd>Whether, when indenting, the first N*<code>tabSize</code>
spaces should be replaced by N tabs. Default is false.</dd>
<dt id="option_electricChars"><code>electricChars (boolean)</code></dt>
<dd>Configures whether the editor should re-indent the current
line when a character is typed that might change its proper
indentation (only works if the mode supports indentation).
Default is true.</dd>
<dt id="option_autoClearEmptyLines"><code>autoClearEmptyLines (boolean)</code></dt>
<dd>When turned on (default is off), this will
automatically clear lines consisting only of whitespace when the
cursor leaves them. This is mostly useful to prevent auto
indentation from introducing trailing whitespace in a file.</dd>
<dt id="option_keyMap"><code>keyMap (string)</code></dt>
<dd>Configures the keymap to use. The default
is <code>"default"</code>, which is the only keymap defined
in <code>codemirror.js</code> itself. Extra keymaps are found in
the <a href="../keymap/"><code>keymap</code></a> directory. See
the <a href="#keymaps">section on keymaps</a> for more
information.</dd>
<dt id="option_extraKeys"><code>extraKeys (object)</code></dt>
<dd>Can be used to specify extra keybindings for the editor,
alongside the ones defined
by <a href="#option_keyMap"><code>keyMap</code></a>. Should be
either null, or a valid <a href="#keymaps">keymap</a> value.</dd>
<dt id="option_lineWrapping"><code>lineWrapping (boolean)</code></dt>
<dd>Whether CodeMirror should scroll or wrap for long lines.
Defaults to <code>false</code> (scroll).</dd>
<dt id="option_lineNumbers"><code>lineNumbers (boolean)</code></dt>
<dd>Whether to show line numbers to the left of the editor.</dd>
<dt id="option_firstLineNumber"><code>firstLineNumber (integer)</code></dt>
<dd>At which number to start counting lines. Default is 1.</dd>
<dt id="option_lineNumberFormatter"><code>lineNumberFormatter (function(integer))</code></dt>
<dd>A function used to format line numbers. The function is passed the current line number. Default prints the line number verbatim.</dd>
<dt id="option_gutter"><code>gutter (boolean)</code></dt>
<dd>Can be used to force a 'gutter' (empty space on the left of
the editor) to be shown even when no line numbers are active.
This is useful for setting <a href="#setMarker">markers</a>.</dd>
<dt id="option_fixedGutter"><code>fixedGutter (boolean)</code></dt>
<dd>When enabled (off by default), this will make the gutter
stay visible when the document is scrolled horizontally.</dd>
<dt id="option_readOnly"><code>readOnly (boolean)</code></dt>
<dd>This disables editing of the editor content by the user. If
the special value <code>"nocursor"</code> is given (instead of
simply <code>true</code>), focusing of the editor is also
disallowed.</dd>
<dt id="option_onChange"><code>onChange (function)</code></dt>
<dd>When given, this function will be called every time the
content of the editor is changed. It will be given the editor
instance as first argument, and an <code>{from, to, text, next}</code>
object containing information about the changes
that occurred as second argument. <code>from</code>
and <code>to</code> are the positions (in the pre-change
coordinate system) where the change started and
ended (for example, it might be <code>{ch:0, line:18}</code> if the
position is at the beginning of line #19). <code>text</code>
is an array of strings representing the text that replaced the changed
range (split by line). If multiple changes happened during a single
operation, the object will have a <code>next</code> property pointing to
another change object (which may point to another, etc).</dd>
<dt id="option_onCursorActivity"><code>onCursorActivity (function)</code></dt>
<dd>Will be called when the cursor or selection moves, or any
change is made to the editor content.</dd>
<dt id="option_onViewportChange"><code>onViewportChange (function)</code></dt>
<dd>When given, will be called whenever
the <a href="#getViewport">view port</a> of the editor changes
(due to scrolling, editing, or any other factor). It will be
passed three arguments, the editor instance, the start of the
viewport, and its end.</dd>
<dt id="option_onGutterClick"><code>onGutterClick (function)</code></dt>
<dd>When given, will be called whenever the editor gutter (the
line-number area) is clicked. Will be given the editor instance
as first argument, the (zero-based) number of the line that was
clicked as second argument, and the raw <code>mousedown</code>
event object as third argument.</dd>
<dt id="option_onFocus"><code>onFocus, onBlur (function)</code></dt>
<dd>The given functions will be called whenever the editor is
focused or unfocused.</dd>
<dt id="option_onScroll"><code>onScroll (function)</code></dt>
<dd>When given, will be called whenever the editor is
scrolled.</dd>
<dt id="option_onUpdate"><code>onUpdate (function)</code></dt>
<dd>Will be called whenever CodeMirror updates its DOM display.</dd>
<dt id="option_matchBrackets"><code>matchBrackets (boolean)</code></dt>
<dd>Determines whether brackets are matched whenever the cursor
is moved next to a bracket.</dd>
<dt id="option_cursorBlinkRate"><code>cursorBlinkRate (number)</code></dt>
<dd>Half-period in milliseconds used for cursor blinking. The default blink
rate is 530ms.</dd>
<dt id="option_workTime"><code>workTime, workDelay (number)</code></dt>
<dd>Highlighting is done by a pseudo background-thread that will
work for <code>workTime</code> milliseconds, and then use
timeout to sleep for <code>workDelay</code> milliseconds. The
defaults are 200 and 300, you can change these options to make
the highlighting more or less aggressive.</dd>
<dt id="option_pollInterval"><code>pollInterval (number)</code></dt>
<dd>Indicates how quickly CodeMirror should poll its input
textarea for changes. Most input is captured by events, but some
things, like IME input on some browsers, doesn't generate events
that allow CodeMirror to properly detect it. Thus, it polls.
Default is 100 milliseconds.</dd>
<dt id="option_undoDepth"><code>undoDepth (integer)</code></dt>
<dd>The maximum number of undo levels that the editor stores.
Defaults to 40.</dd>
<dt id="option_tabindex"><code>tabindex (integer)</code></dt>
<dd>The <a href="http://www.w3.org/TR/html401/interact/forms.html#adef-tabindex">tab
index</a> to assign to the editor. If not given, no tab index
will be assigned.</dd>
<dt id="option_autofocus"><code>autofocus (boolean)</code></dt>
<dd>Can be used to make CodeMirror focus itself on
initialization. Defaults to off.
When <a href="#fromTextArea"><code>fromTextArea</code></a> is
used, and no explicit value is given for this option, it will be
set to true when either the source textarea is focused, or it
has an <code>autofocus</code> attribute and no other element is
focused.</dd>
<dt id="option_dragDrop"><code>dragDrop (boolean)</code></dt>
<dd>Controls whether drag-and-drop is enabled. On by default.</dd>
<dt id="option_onDragEvent"><code>onDragEvent (function)</code></dt>
<dd>When given, this will be called when the editor is handling
a <code>dragenter</code>, <code>dragover</code>,
or <code>drop</code> event. It will be passed the editor instance
and the event object as arguments. The callback can choose to
handle the event itself, in which case it should
return <code>true</code> to indicate that CodeMirror should not
do anything further.</dd>
<dt id="option_onKeyEvent"><code>onKeyEvent (function)</code></dt>
<dd>This provides a rather low-level hook into CodeMirror's key
handling. If provided, this function will be called on
every <code>keydown</code>, <code>keyup</code>,
and <code>keypress</code> event that CodeMirror captures. It
will be passed two arguments, the editor instance and the key
event. This key event is pretty much the raw key event, except
that a <code>stop()</code> method is always added to it. You
could feed it to, for example, <code>jQuery.Event</code> to
further normalize it.<br>This function can inspect the key
event, and handle it if it wants to. It may return true to tell
CodeMirror to ignore the event. Be wary that, on some browsers,
stopping a <code>keydown</code> does not stop
the <code>keypress</code> from firing, whereas on others it
does. If you respond to an event, you should probably inspect
its <code>type</code> property and only do something when it
is <code>keydown</code> (or <code>keypress</code> for actions
that need character data).</dd>
</dl>
<h2 id="keymaps">Keymaps</h2>
<p>Keymaps are ways to associate keys with functionality. A keymap
is an object mapping strings that identify the keys to functions
that implement their functionality.</p>
<p>Keys are identified either by name or by character.
The <code>CodeMirror.keyNames</code> object defines names for
common keys and associates them with their key codes. Examples of
names defined here are <code>Enter</code>, <code>F5</code>,
and <code>Q</code>. These can be prefixed
with <code>Shift-</code>, <code>Cmd-</code>, <code>Ctrl-</code>,
and <code>Alt-</code> (in that order!) to specify a modifier. So
for example, <code>Shift-Ctrl-Space</code> would be a valid key
identifier.</p>
<p>Alternatively, a character can be specified directly by
surrounding it in single quotes, for example <code>'$'</code>
or <code>'q'</code>. Due to limitations in the way browsers fire
key events, these may not be prefixed with modifiers.</p>
<p>The <code>CodeMirror.keyMap</code> object associates keymaps
with names. User code and keymap definitions can assign extra
properties to this object. Anywhere where a keymap is expected, a
string can be given, which will be looked up in this object. It
also contains the <code>"default"</code> keymap holding the
default bindings.</p>
<p>The values of properties in keymaps can be either functions of
a single argument (the CodeMirror instance), strings, or
<code>false</code>. Such strings refer to properties of the
<code>CodeMirror.commands</code> object, which defines a number of
common commands that are used by the default keybindings, and maps
them to functions. If the property is set to <code>false</code>,
CodeMirror leaves handling of the key up to the browser. A key
handler function may throw <code>CodeMirror.Pass</code> to indicate
that it has decided not to handle the key, and other handlers (or
the default behavior) should be given a turn.</p>
<p>Keys mapped to command names that start with the
characters <code>"go"</code> (which should be used for
cursor-movement actions) will be fired even when an
extra <code>Shift</code> modifier is present (i.e. <code>"Up":
"goLineUp"</code> matches both up and shift-up). This is used to
easily implement shift-selection.</p>
<p>Keymaps can defer to each other by defining
a <code>fallthrough</code> property. This indicates that when a
key is not found in the map itself, one or more other maps should
be searched. It can hold either a single keymap or an array of
keymaps.</p>
<p>When a keymap contains a <code>nofallthrough</code> property
set to <code>true</code>, keys matched against that map will be
ignored if they don't match any of the bindings in the map (no
further child maps will be tried, and the default effect of
inserting a character will not occur).</p>
<h2 id="styling">Customized Styling</h2>
<p>Up to a certain extent, CodeMirror's look can be changed by
modifying style sheet files. The style sheets supplied by modes
simply provide the colors for that mode, and can be adapted in a
very straightforward way. To style the editor itself, it is
possible to alter or override the styles defined
in <a href="../lib/codemirror.css"><code>codemirror.css</code></a>.</p>
<p>Some care must be taken there, since a lot of the rules in this
file are necessary to have CodeMirror function properly. Adjusting
colors should be safe, of course, and with some care a lot of
other things can be changed as well. The CSS classes defined in
this file serve the following roles:</p>
<dl>
<dt id="class_CodeMirror"><code>CodeMirror</code></dt>
<dd>The outer element of the editor. This should be used for the
editor width, borders and positioning. Can also be used to set
styles that should hold for everything inside the editor (such
as font and font size), or to set a background.</dd>
<dt id="class_CodeMirror_scroll"><code>CodeMirror-scroll</code></dt>
<dd>This determines the editor's height, and whether the editor
scrolls (<code>overflow: auto</code> + fixed height). By
default, it does. Giving this <code>height: auto; overflow:
visible;</code> will cause the editor to resize to fit its
content.</dd>
<dt id="class_CodeMirror_focused"><code>CodeMirror-focused</code></dt>
<dd>Whenever the editor is focused, the top element gets this
class. This is used to hide the cursor and give the selection a
different color when the editor is not focused.</dd>
<dt id="class_CodeMirror_gutter"><code>CodeMirror-gutter</code></dt>
<dd>Use this for giving a background or a border to the editor
gutter. Don't set any padding here,
use <code>CodeMirror-gutter-text</code> for that. By default,
the gutter is 'fluid', meaning it will adjust its width to the
maximum line number or line marker width. You can also set a
fixed width if you want.</dd>
<dt id="class_CodeMirror_gutter_text"><code>CodeMirror-gutter-text</code></dt>
<dd>Used to style the actual line numbers. For the numbers to
line up, you must make sure that the font in the gutter is the
same as the one in the rest of the editor, so you should
probably only set font style and size in
the <code>CodeMirror</code> class.</dd>
<dt id="class_CodeMirror_lines"><code>CodeMirror-lines</code></dt>
<dd>The visible lines. If this has vertical
padding, <code>CodeMirror-gutter</code> should have the same
padding.</dd>
<dt id="class_CodeMirror_cursor"><code>CodeMirror-cursor</code></dt>
<dd>The cursor is a block element that is absolutely positioned.
You can make it look whichever way you want.</dd>
<dt id="class_CodeMirror_selected"><code>CodeMirror-selected</code></dt>
<dd>The selection is represented by <code>span</code> elements
with this class.</dd>
<dt id="class_CodeMirror_matchingbracket"><code>CodeMirror-matchingbracket</code>,
<code>CodeMirror-nonmatchingbracket</code></dt>
<dd>These are used to style matched (or unmatched) brackets.</dd>
</dl>
<p id="css-resize">So note carefully that, in order to resize the
editor, you should set a <code>width</code> on
the <a href="#getWrapperElement">wrapper</a>
(class <code>CodeMirror</code>) element, and a height on
the <a href="#getScrollerElement">scroller</a>
(class <code>CodeMirror-scroll</code>) element.</p>
<p>The actual lines, as well as the cursor, are represented
by <code>pre</code> elements. By default no text styling (such as
bold) that might change line height is applied. If you do want
such effects, you'll have to give <code>CodeMirror pre</code> a
fixed height.</p>
<p>If your page's style sheets do funky things to
all <code>div</code> or <code>pre</code> elements (you probably
shouldn't do that), you'll have to define rules to cancel these
effects out again for elements under the <code>CodeMirror</code>
class.</p>
<p>Themes are also simply CSS files, which define colors for
various syntactic elements. See the files in
the <a href="../theme/"><code>theme</code></a> directory.</p>
<h2 id="api">Programming API</h2>
<p>A lot of CodeMirror features are only available through its API.
This has the disadvantage that you need to do work to enable them,
and the advantage that CodeMirror will fit seamlessly into your
application.</p>
<p>Whenever points in the document are represented, the API uses
objects with <code>line</code> and <code>ch</code> properties.
Both are zero-based. CodeMirror makes sure to 'clip' any positions
passed by client code so that they fit inside the document, so you
shouldn't worry too much about sanitizing your coordinates. If you
give <code>ch</code> a value of <code>null</code>, or don't
specify it, it will be replaced with the length of the specified
line.</p>
<dl>
<dt id="getValue"><code>getValue() → string</code></dt>
<dd>Get the current editor content. You can pass it an optional
argument to specify the string to be used to separate lines
(defaults to <code>"\n"</code>).</dd>
<dt id="setValue"><code>setValue(string)</code></dt>
<dd>Set the editor content.</dd>
<dt id="getSelection"><code>getSelection() → string</code></dt>
<dd>Get the currently selected code.</dd>
<dt id="replaceSelection"><code>replaceSelection(string)</code></dt>
<dd>Replace the selection with the given string.</dd>
<dt id="setSize"><code>setSize(width, height)</code></dt>
<dd>Programatically set the size of the editor (overriding the
applicable <a href="#css-resize">CSS
rules</a>). <code>width</code> and <code>height</code> height
can be either numbers (interpreted as pixels) or CSS units
(<code>"100%"</code>, for example). You can
pass <code>null</code> for either of them to indicate that that
dimension should not be changed.</dd>
<dt id="focus"><code>focus()</code></dt>
<dd>Give the editor focus.</dd>
<dt id="scrollTo"><code>scrollTo(x, y)</code></dt>
<dd>Scroll the editor to a given (pixel) position. Both
arguments may be left as <code>null</code>
or <code>undefined</code> to have no effect.</dd>
<dt id="getScrollInfo"><code>getScrollInfo()</code></dt>
<dd>Get an <code>{x, y, width, height}</code> object that
represents the current scroll position and scrollable area size
of the editor.</dd>
<dt id="setOption"><code>setOption(option, value)</code></dt>
<dd>Change the configuration of the editor. <code>option</code>
should the name of an <a href="#config">option</a>,
and <code>value</code> should be a valid value for that
option.</dd>
<dt id="getOption"><code>getOption(option) → value</code></dt>
<dd>Retrieves the current value of the given option for this
editor instance.</dd>
<dt id="getMode"><code>getMode() → object</code></dt>
<dd>Gets the mode object for the editor. Note that this is
distinct from <code>getOption("mode")</code>, which gives you
the mode specification, rather than the resolved, instantiated
<a href="#defineMode">mode object</a>.</dd>
<dt id="cursorCoords"><code>cursorCoords(start, mode) → object</code></dt>
<dd>Returns an <code>{x, y, yBot}</code> object containing the
coordinates of the cursor. If <code>mode</code>
is <code>"local"</code>, they will be relative to the top-left
corner of the editable document. If it is <code>"page"</code> or
not given, they are relative to the top-left corner of the
page. <code>yBot</code> is the coordinate of the bottom of the
cursor. <code>start</code> is a boolean indicating whether you
want the start or the end of the selection.</dd>
<dt id="charCoords"><code>charCoords(pos, mode) → object</code></dt>
<dd>Like <code>cursorCoords</code>, but returns the position of
an arbitrary characters. <code>pos</code> should be
a <code>{line, ch}</code> object.</dd>
<dt id="coordsChar"><code>coordsChar(object) → pos</code></dt>
<dd>Given an <code>{x, y}</code> object (in page coordinates),
returns the <code>{line, ch}</code> position that corresponds to
it.</dd>
<dt id="undo"><code>undo()</code></dt>
<dd>Undo one edit (if any undo events are stored).</dd>
<dt id="redo"><code>redo()</code></dt>
<dd>Redo one undone edit.</dd>
<dt id="historySize"><code>historySize() → object</code></dt>
<dd>Returns an object with <code>{undo, redo}</code> properties,
both of which hold integers, indicating the amount of stored
undo and redo operations.</dd>
<dt id="clearHistory"><code>clearHistory()</code></dt>
<dd>Clears the editor's undo history.</dd>
<dt id="getHistory"><code>getHistory() → object</code></dt>
<dd>Get a (JSON-serializeable) representation of the undo history.</dd>
<dt id="setHistory"><code>setHistory(object)</code></dt>
<dd>Replace the editor's undo history with the one provided,
which must be a value as returned
by <a href="#getHistory"><code>getHistory</code></a>. Note that
this will have entirely undefined results if the editor content
isn't also the same as it was when <code>getHistory</code> was
called.</dd>
<dt id="indentLine"><code>indentLine(line, dir)</code></dt>
<dd>Reset the given line's indentation to the indentation
prescribed by the mode. If the second argument is given,
indentation will be increased (if <code>dir</code> is true) or
decreased (if false) by an <a href="#option_indentUnit">indent
unit</a> instead.</dd>
<dt id="getTokenAt"><code>getTokenAt(pos) → object</code></dt>
<dd>Retrieves information about the token the current mode found
before the given position (a <code>{line, ch}</code> object). The
returned object has the following properties:
<dl>
<dt><code>start</code></dt><dd>The character (on the given line) at which the token starts.</dd>
<dt><code>end</code></dt><dd>The character at which the token ends.</dd>
<dt><code>string</code></dt><dd>The token's string.</dd>
<dt><code>className</code></dt><dd>The class the mode assigned
to the token. (Can be null when no class was assigned.)</dd>
<dt><code>state</code></dt><dd>The mode's state at the end of this token.</dd>
</dl></dd>
<dt id="markText"><code>markText(from, to, className, options) → object</code></dt>
<dd>Can be used to mark a range of text with a specific CSS
class name. <code>from</code> and <code>to</code> should
be <code>{line, ch}</code> objects. The <code>options</code>
parameter is optional. When given, it should be an object that
may contain the following configuration options:
<dl>
<dt><code>inclusiveLeft</code></dt><dd>Determines whether
text inserted on the left of the marker will end up inside
or outside of it.</dd>
<dt><code>inclusiveRight</code></dt><dd>Like <code>inclusiveLeft</code>,
but for the right side.</dd>
<dt><code>startStyle</code></dt><dd>Can be used to specify
an extra CSS class to be applied to the leftmost span that
is part of the marker.</dd>
<dt><code>endStyle</code></dt><dd>Equivalent
to <code>startStyle</code>, but for the rightmost span.</dd>
</dl>
The method will return an object with two methods,
<code>clear()</code>, which removes the mark,
and <code>find()</code>, which returns a <code>{from, to}</code>
(both document positions), indicating the current position of
the marked range, or <code>undefined</code> if the marker is no
longer in the document.</dd>
<dt id="setBookmark"><code>setBookmark(pos) → object</code></dt>
<dd>Inserts a bookmark, a handle that follows the text around it
as it is being edited, at the given position. A bookmark has two
methods <code>find()</code> and <code>clear()</code>. The first
returns the current position of the bookmark, if it is still in
the document, and the second explicitly removes the
bookmark.</dd>
<dt id="findMarksAt"><code>findMarksAt(pos) → array</code></dt>
<dd>Returns an array of all the bookmarks and marked ranges
present at the given position.</dd>
<dt id="setMarker"><code>setMarker(line, text, className) → lineHandle</code></dt>
<dd>Add a gutter marker for the given line. Gutter markers are
shown in the line-number area (instead of the number for this
line). Both <code>text</code> and <code>className</code> are
optional. Setting <code>text</code> to a Unicode character like
● tends to give a nice effect. To put a picture in the gutter,
set <code>text</code> to a space and <code>className</code> to
something that sets a background image. If you
specify <code>text</code>, the given text (which may contain
HTML) will, by default, replace the line number for that line.
If this is not what you want, you can include the
string <code>%N%</code> in the text, which will be replaced by
the line number.</dd>
<dt id="clearMarker"><code>clearMarker(line)</code></dt>
<dd>Clears a marker created
with <code>setMarker</code>. <code>line</code> can be either a
number or a handle returned by <code>setMarker</code> (since a
number may now refer to a different line if something was added
or deleted).</dd>
<dt id="setLineClass"><code>setLineClass(line, className, backgroundClassName) → lineHandle</code></dt>
<dd>Set a CSS class name for the given line. <code>line</code>
can be a number or a line handle (as returned
by <code>setMarker</code> or this
function). <code>className</code> will be used to style the text
for the line, and <code>backgroundClassName</code> to style its
background (which lies behind the selection).
Pass <code>null</code> to clear the classes for a line.</dd>
<dt id="hideLine"><code>hideLine(line) → lineHandle</code></dt>
<dd>Hide the given line (either by number or by handle). Hidden
lines don't show up in the editor, and their numbers are skipped
when <a href="#option_lineNumbers">line numbers</a> are enabled.
Deleting a region around them does delete them, and coping a
region around will include them in the copied text.</dd>
<dt id="showLine"><code>showLine(line) → lineHandle</code></dt>
<dd>The inverse of <code>hideLine</code>—re-shows a previously
hidden line, by number or by handle.</dd>
<dt id="onDeleteLine"><code>onDeleteLine(line, func)</code></dt>
<dd>Register a function that should be called when the line is
deleted from the document.</dd>
<dt id="lineInfo"><code>lineInfo(line) → object</code></dt>
<dd>Returns the line number, text content, and marker status of
the given line, which can be either a number or a handle
returned by <code>setMarker</code>. The returned object has the
structure <code>{line, handle, text, markerText, markerClass,
lineClass, bgClass}</code>.</dd>
<dt id="getLineHandle"><code>getLineHandle(num) → lineHandle</code></dt>
<dd>Fetches the line handle for the given line number.</dd>
<dt id="getViewport"><code>getViewport() → object</code></dt>
<dd>Returns a <code>{from, to}</code> object indicating the
start (inclusive) and end (exclusive) of the currently displayed
part of the document. In big documents, when most content is
scrolled out of view, CodeMirror will only render the visible
part, and a margin around it. See also
the <a href="#option_onViewportChange"><code>onViewportChange</code></a>
option.</dd>
<dt id="addWidget"><code>addWidget(pos, node, scrollIntoView)</code></dt>
<dd>Puts <code>node</code>, which should be an absolutely
positioned DOM node, into the editor, positioned right below the
given <code>{line, ch}</code> position.
When <code>scrollIntoView</code> is true, the editor will ensure
that the entire node is visible (if possible). To remove the
widget again, simply use DOM methods (move it somewhere else, or
call <code>removeChild</code> on its parent).</dd>
<dt id="matchBrackets"><code>matchBrackets()</code></dt>
<dd>Force matching-bracket-highlighting to happen.</dd>
<dt id="lineCount"><code>lineCount() → number</code></dt>
<dd>Get the number of lines in the editor.</dd>
<dt id="getCursor"><code>getCursor(start) → object</code></dt>
<dd><code>start</code> is a boolean indicating whether the start
or the end of the selection must be retrieved. If it is not
given, the current cursor pos, i.e. the side of the selection
that would move if you pressed an arrow key, is chosen.
A <code>{line, ch}</code> object will be returned.</dd>
<dt id="somethingSelected"><code>somethingSelected() → boolean</code></dt>
<dd>Return true if any text is selected.</dd>
<dt id="setCursor"><code>setCursor(pos)</code></dt>
<dd>Set the cursor position. You can either pass a
single <code>{line, ch}</code> object, or the line and the
character as two separate parameters.</dd>
<dt id="setSelection"><code>setSelection(start, end)</code></dt>
<dd>Set the selection range. <code>start</code>
and <code>end</code> should be <code>{line, ch}</code> objects.</dd>
<dt id="getLine"><code>getLine(n) → string</code></dt>
<dd>Get the content of line <code>n</code>.</dd>
<dt id="setLine"><code>setLine(n, text)</code></dt>
<dd>Set the content of line <code>n</code>.</dd>
<dt id="removeLine"><code>removeLine(n)</code></dt>
<dd>Remove the given line from the document.</dd>
<dt id="getRange"><code>getRange(from, to) → string</code></td>
<dd>Get the text between the given points in the editor, which
should be <code>{line, ch}</code> objects. An optional third
argument can be given to indicate the line separator string to
use (defaults to <code>"\n"</code>).</dd>
<dt id="replaceRange"><code>replaceRange(string, from, to)</code></dt>
<dd>Replace the part of the document between <code>from</code>
and <code>to</code> with the given string. <code>from</code>
and <code>to</code> must be <code>{line, ch}</code>
objects. <code>to</code> can be left off to simply insert the
string at position <code>from</code>.</dd>
<dt id="posFromIndex"><code>posFromIndex(index) → object</code></dt>
<dd>Calculates and returns a <code>{line, ch}</code> object for a
zero-based <code>index</code> who's value is relative to the start of the
editor's text. If the <code>index</code> is out of range of the text then
the returned object is clipped to start or end of the text
respectively.</dd>
<dt id="indexFromPos"><code>indexFromPos(object) → number</code></dt>
<dd>The reverse of <a href="#posFromIndex"><code>posFromIndex</code></a>.</dd>
</dl>
<p>The following are more low-level methods:</p>
<dl>
<dt id="operation"><code>operation(func) → result</code></dt>
<dd>CodeMirror internally buffers changes and only updates its
DOM structure after it has finished performing some operation.
If you need to perform a lot of operations on a CodeMirror
instance, you can call this method with a function argument. It
will call the function, buffering up all changes, and only doing
the expensive update after the function returns. This can be a
lot faster. The return value from this method will be the return
value of your function.</dd>
<dt id="compoundChange"><code>compoundChange(func) → result</code></dt>
<dd>Will call the given function (and return its result),
combining all changes made while that function executes into a
single undo event.</dd>
<dt id="refresh"><code>refresh()</code></dt>
<dd>If your code does something to change the size of the editor
element (window resizes are already listened for), or unhides
it, you should probably follow up by calling this method to
ensure CodeMirror is still looking as intended.</dd>
<dt id="getInputField"><code>getInputField() → textarea</code></dt>
<dd>Returns the hidden textarea used to read input.</dd>
<dt id="getWrapperElement"><code>getWrapperElement() → node</code></dt>
<dd>Returns the DOM node that represents the editor, and
controls its width. Remove this from your tree to delete an
editor instance. Set it's <code>width</code> style when
resizing.</dd>
<dt id="getScrollerElement"><code>getScrollerElement() → node</code></dt>
<dd>Returns the DOM node that is responsible for the vertical
sizing and horizontal scrolling of the editor. You can change
the <code>height</code> style of this element to resize an
editor. (You might have to call
the <a href="#refresh"><code>refresh</code></a> method
afterwards.)</dd>
<dt id="getGutterElement"><code>getGutterElement() → node</code></dt>
<dd>Fetches the DOM node that represents the editor gutter.</dd>
<dt id="getStateAfter"><code>getStateAfter(line) → state</code></dt>
<dd>Returns the mode's parser state, if any, at the end of the
given line number. If no line number is given, the state at the
end of the document is returned. This can be useful for storing
parsing errors in the state, or getting other kinds of
contextual information for a line.</dd>
</dl>
<p id="version">The <code>CodeMirror</code> object itself provides
several useful properties. Firstly, its <code>version</code>
property contains a string that indicates the version of the
library. For releases, this simply
contains <code>"major.minor"</code> (for
example <code>"2.33"</code>. For beta versions, <code>" B"</code>
(space, capital B) is added at the end of the string, for
development snapshots, <code>" +"</code> (space, plus) is
added.</p>
<p id="fromTextArea">The <code>CodeMirror.fromTextArea</code>
method provides another way to initialize an editor. It takes a
textarea DOM node as first argument and an optional configuration
object as second. It will replace the textarea with a CodeMirror
instance, and wire up the form of that textarea (if any) to make
sure the editor contents are put into the textarea when the form
is submitted. A CodeMirror instance created this way has three
additional methods:</p>
<dl>
<dt id="save"><code>save()</code></dt>
<dd>Copy the content of the editor into the textarea.</dd>
<dt id="toTextArea"><code>toTextArea()</code></dt>
<dd>Remove the editor, and restore the original textarea (with
the editor's current content).</dd>
<dt id="getTextArea"><code>getTextArea() → textarea</code></dt>
<dd>Returns the textarea that the instance was based on.</dd>
</dl>
<p id="defineExtension">If you want to define extra methods in terms
of the CodeMirror API, it is possible to
use <code>CodeMirror.defineExtension(name, value)</code>. This
will cause the given value (usually a method) to be added to all
CodeMirror instances created from then on.</p>
<p id="defineInitHook">If your extention just needs to run some
code whenever a CodeMirror instance is initialized,
use <code>CodeMirror.defineInitHook</code>. Give it a function as
its only argument, and from then on, that function will be called
(with the instance as argument) whenever a new CodeMirror instance
is initialized.</p>
<h2 id="addons">Add-ons</h2>
<p>The <code>lib/util</code> directory in the distribution
contains a number of reusable components that implement extra
editor functionality. In brief, they are:</p>
<dl>
<dt id="util_dialog"><a href="../lib/util/dialog.js"><code>dialog.js</code></a></dt>
<dd>Provides a very simple way to query users for text input.
Adds an <code>openDialog</code> method to CodeMirror instances,
which can be called with an HTML fragment that provides the
prompt (should include an <code>input</code> tag), and a
callback function that is called when text has been entered.
Depends on <code>lib/util/dialog.css</code>.</dd>
<dt id="util_searchcursor"><a href="../lib/util/searchcursor.js"><code>searchcursor.js</code></a></dt>
<dd>Adds the <code>getSearchCursor(query, start, caseFold) →
cursor</code> method to CodeMirror instances, which can be used
to implement search/replace functionality. <code>query</code>
can be a regular expression or a string (only strings will match
across lines—if they contain newlines). <code>start</code>
provides the starting position of the search. It can be
a <code>{line, ch}</code> object, or can be left off to default
to the start of the document. <code>caseFold</code> is only
relevant when matching a string. It will cause the search to be
case-insensitive. A search cursor has the following methods:
<dl>
<dt><code>findNext(), findPrevious() → boolean</code></dt>
<dd>Search forward or backward from the current position.
The return value indicates whether a match was found. If
matching a regular expression, the return value will be the
array returned by the <code>match</code> method, in case you
want to extract matched groups.</dd>
<dt><code>from(), to() → object</code></dt>
<dd>These are only valid when the last call
to <code>findNext</code> or <code>findPrevious</code> did
not return false. They will return <code>{line, ch}</code>
objects pointing at the start and end of the match.</dd>
<dt><code>replace(text)</code></dt>
<dd>Replaces the currently found match with the given text
and adjusts the cursor position to reflect the
replacement.</dd>
</dl></dd>
<dt id="util_search"><a href="../lib/util/search.js"><code>search.js</code></a></dt>
<dd>Implements the search commands. CodeMirror has keys bound to
these by default, but will not do anything with them unless an
implementation is provided. Depends
on <code>searchcursor.js</code>, and will make use
of <a href="#util_dialog"><code>openDialog</code></a> when
available to make prompting for search queries less ugly.</dd>
<dt id="util_foldcode"><a href="../lib/util/foldcode.js"><code>foldcode.js</code></a></dt>
<dd>Helps with code folding.
See <a href="../demo/folding.html">the demo</a> for an example.
Call <code>CodeMirror.newFoldFunction</code> with a range-finder
helper function to create a function that will, when applied to
a CodeMirror instance and a line number, attempt to fold or
unfold the block starting at the given line. A range-finder is a
language-specific function that also takes an instance and a
line number, and returns an end line for the block, or null if
no block is started on that line. This file
provides <code>CodeMirror.braceRangeFinder</code>, which finds
blocks in brace languages (JavaScript, C, Java,
etc), <code>CodeMirror.indentRangeFinder</code>, for languages
where indentation determines block structure (Python, Haskell),
and <code>CodeMirror.tagRangeFinder</code>, for XML-style
languages.</dd>
<dt id="util_runmode"><a href="../lib/util/runmode.js"><code>runmode.js</code></a></dt>
<dd>Can be used to run a CodeMirror mode over text without
actually opening an editor instance.
See <a href="../demo/runmode.html">the demo</a> for an
example.</dd>
<dt id="util_overlay"><a href="../lib/util/overlay.js"><code>overlay.js</code></a></dt>
<dd>Mode combinator that can be used to extend a mode with an
'overlay' — a secondary mode is run over the stream, along with
the base mode, and can color specific pieces of text without
interfering with the base mode.
Defines <code>CodeMirror.overlayMode</code>, which is used to
create such a mode. See <a href="../demo/mustache.html">this
demo</a> for a detailed example.</dd>
<dt id="util_multiplex"><a href="../lib/util/multiplex.js"><code>multiplex.js</code></a></dt>
<dd>Mode combinator that can be used to easily 'multiplex'
between several modes.
Defines <code>CodeMirror.multiplexingMode</code> which, when
given as first argument a mode object, and as other arguments
any number of <code>{open, close, mode [, delimStyle]}</code>
objects, will return a mode object that starts parsing using the
mode passed as first argument, but will switch to another mode
as soon as it encounters a string that occurs in one of
the <code>open</code> fields of the passed objects. When in a
sub-mode, it will go back to the top mode again when
the <code>close</code> string is encountered.
When <code>delimStyle</code> is specified, it will be the token
style returned for the delimiter tokens. The outer mode will not
see the content between the delimiters.
See <a href="../demo/multiplex.html">this demo</a> for an
example.</dd>
<dt id="util_simple-hint"><a href="../lib/util/simple-hint.js"><code>simple-hint.js</code></a></dt>
<dd>Provides a framework for showing autocompletion hints.
Defines <code>CodeMirror.simpleHint</code>, which takes a
CodeMirror instance and a hinting function, and pops up a widget
that allows the user to select a completion. Hinting functions
are function that take an editor instance, and return
a <code>{list, from, to}</code> object, where <code>list</code>
is an array of strings (the completions), and <code>from</code>
and <code>to</code> give the start and end of the token that is
being completed. Depends
on <code>lib/util/simple-hint.css</code>.</dd>
<dt id="util_javascript-hint"><a href="../lib/util/javascript-hint.js"><code>javascript-hint.js</code></a></dt>
<dd>Defines <code>CodeMirror.javascriptHint</code>
and <code>CodeMirror.coffeescriptHint</code>, which are simple
hinting functions for the JavaScript and CoffeeScript
modes.</dd>
<dt id="util_match-highlighter"><a href="../lib/util/match-highlighter.js"><code>match-highlighter.js</code></a></dt>
<dd>Adds a <code>matchHighlight</code> method to CodeMirror
instances that can be called (typically from
a <a href="#option_onCursorActivity"><code>onCursorActivity</code></a>
handler) to highlight all instances of a currently selected word
with the a classname given as a first argument to the method.
Depends on
the <a href="#util_searchcursor"><code>searchcursor</code></a>
add-on. Demo <a href="../demo/matchhighlighter.html">here</a>.</dd>
<dt id="util_formatting"><a href="../lib/util/formatting.js"><code>formatting.js</code></a></dt>
<dd>Adds <code>commentRange</code>, <code>autoIndentRange</code>,
and <code>autoFormatRange</code> methods that, respectively,
comment (or uncomment), indent, or format (add line breaks) a
range of code. <a href="../demo/formatting.html">Demo here.</a></dd>
<dt id="util_closetag"><a href="../lib/util/closetag.js"><code>closetag.js</code></a></dt>
<dd>Provides utility functions for adding automatic tag closing
to XML modes. See
the <a href="../demo/closetag.html">demo</a>.</dd>
<dt id="util_loadmode"><a href="../lib/util/loadmode.js"><code>loadmode.js</code></a></dt>
<dd>Defines a <code>CodeMirror.requireMode(modename,
callback)</code> function that will try to load a given mode and
call the callback when it succeeded. You'll have to
set <code>CodeMirror.modeURL</code> to a string that mode paths
can be constructed from, for
example <code>"mode/%N/%N.js"</code>—the <code>%N</code>'s will
be replaced with the mode name. Also
defines <code>CodeMirror.autoLoadMode(instance, mode)</code>,
which will ensure the given mode is loaded and cause the given
editor instance to refresh its mode when the loading
succeeded. See the <a href="../demo/loadmode.html">demo</a>.</dd>
</dl>
<h2 id="modeapi">Writing CodeMirror Modes</h2>
<p>Modes typically consist of a single JavaScript file. This file
defines, in the simplest case, a lexer (tokenizer) for your
language—a function that takes a character stream as input,
advances it past a token, and returns a style for that token. More
advanced modes can also handle indentation for the language.</p>
<p id="defineMode">The mode script should
call <code>CodeMirror.defineMode</code> to register itself with
CodeMirror. This function takes two arguments. The first should be
the name of the mode, for which you should use a lowercase string,
preferably one that is also the name of the files that define the
mode (i.e. <code>"xml"</code> is defined <code>xml.js</code>). The
second argument should be a function that, given a CodeMirror
configuration object (the thing passed to
the <code>CodeMirror</code> function) and an optional mode
configuration object (as in
the <a href="#option_mode"><code>mode</code></a> option), returns
a mode object.</p>
<p>Typically, you should use this second argument
to <code>defineMode</code> as your module scope function (modes
should not leak anything into the global scope!), i.e. write your
whole mode inside this function.</p>
<p>The main responsibility of a mode script is <em>parsing</em>
the content of the editor. Depending on the language and the
amount of functionality desired, this can be done in really easy
or extremely complicated ways. Some parsers can be stateless,
meaning that they look at one element (<em>token</em>) of the code
at a time, with no memory of what came before. Most, however, will
need to remember something. This is done by using a <em>state
object</em>, which is an object that is always passed when
reading a token, and which can be mutated by the tokenizer.</p>
<p id="startState">Modes that use a state must define
a <code>startState</code> method on their mode object. This is a
function of no arguments that produces a state object to be used
at the start of a document.</p>
<p id="token">The most important part of a mode object is
its <code>token(stream, state)</code> method. All modes must
define this method. It should read one token from the stream it is
given as an argument, optionally update its state, and return a
style string, or <code>null</code> for tokens that do not have to
be styled. For your styles, you can either use the 'standard' ones
defined in the themes (without the <code>cm-</code> prefix), or
define your own and have people include a custom CSS file for your
mode.<p>
<p id="StringStream">The stream object encapsulates a line of code
(tokens may never span lines) and our current position in that
line. It has the following API:</p>
<dl>
<dt><code>eol() → boolean</code></dt>
<dd>Returns true only if the stream is at the end of the
line.</dd>
<dt><code>sol() → boolean</code></dt>
<dd>Returns true only if the stream is at the start of the
line.</dd>
<dt><code>peek() → character</code></dt>
<dd>Returns the next character in the stream without advancing
it. Will return an empty string at the end of the line.</dd>
<dt><code>next() → character</code></dt>
<dd>Returns the next character in the stream and advances it.
Also returns <code>undefined</code> when no more characters are
available.</dd>
<dt><code>eat(match) → character</code></dt>
<dd><code>match</code> can be a character, a regular expression,
or a function that takes a character and returns a boolean. If
the next character in the stream 'matches' the given argument,
it is consumed and returned. Otherwise, <code>undefined</code>
is returned.</dd>
<dt><code>eatWhile(match) → boolean</code></dt>
<dd>Repeatedly calls <code>eat</code> with the given argument,
until it fails. Returns true if any characters were eaten.</dd>
<dt><code>eatSpace() → boolean</code></dt>
<dd>Shortcut for <code>eatWhile</code> when matching
white-space.</dd>
<dt><code>skipToEnd()</code></dt>
<dd>Moves the position to the end of the line.</dd>
<dt><code>skipTo(ch) → boolean</code></dt>
<dd>Skips to the next occurrence of the given character, if
found on the current line (doesn't advance the stream if the
character does not occur on the line). Returns true if the
character was found.</dd>
<dt><code>match(pattern, consume, caseFold) → boolean</code></dt>
<dd>Act like a
multi-character <code>eat</code>—if <code>consume</code> is true
or not given—or a look-ahead that doesn't update the stream
position—if it is false. <code>pattern</code> can be either a
string or a regular expression starting with <code>^</code>.
When it is a string, <code>caseFold</code> can be set to true to
make the match case-insensitive. When successfully matching a
regular expression, the returned value will be the array
returned by <code>match</code>, in case you need to extract
matched groups.</dd>
<dt><code>backUp(n)</code></dt>
<dd>Backs up the stream <code>n</code> characters. Backing it up
further than the start of the current token will cause things to
break, so be careful.</dd>
<dt><code>column() → integer</code></dt>
<dd>Returns the column (taking into account tabs) at which the
current token starts. Can be used to find out whether a token
starts a new line.</dd>
<dt><code>indentation() → integer</code></dt>
<dd>Tells you how far the current line has been indented, in
spaces. Corrects for tab characters.</dd>
<dt><code>current() → string</code></dt>
<dd>Get the string between the start of the current token and
the current stream position.</dd>
</dl>
<p id="blankLine">By default, blank lines are simply skipped when
tokenizing a document. For languages that have significant blank
lines, you can define a <code>blankLine(state)</code> method on
your mode that will get called whenever a blank line is passed
over, so that it can update the parser state.</p>
<p id="copyState">Because state object are mutated, and CodeMirror
needs to keep valid versions of a state around so that it can
restart a parse at any line, copies must be made of state objects.
The default algorithm used is that a new state object is created,
which gets all the properties of the old object. Any properties
which hold arrays get a copy of these arrays (since arrays tend to
be used as mutable stacks). When this is not correct, for example
because a mode mutates non-array properties of its state object, a
mode object should define a <code>copyState</code> method,
which is given a state and should return a safe copy of that
state.</p>
<p id="indent">If you want your mode to provide smart indentation
(through the <a href="#indentLine"><code>indentLine</code></a>
method and the <code>indentAuto</code>
and <code>newlineAndIndent</code> commands, which keys can be
<a href="#option_extraKeys">bound</a> to), you must define
an <code>indent(state, textAfter)</code> method on your mode
object.</p>
<p>The indentation method should inspect the given state object,
and optionally the <code>textAfter</code> string, which contains
the text on the line that is being indented, and return an
integer, the amount of spaces to indent. It should usually take
the <a href="#option_indentUnit"><code>indentUnit</code></a>
option into account.</p>
<p id="electricChars">Finally, a mode may define
an <code>electricChars</code> property, which should hold a string
containing all the characters that should trigger the behaviour
described for
the <a href="#option_electricChars"><code>electricChars</code></a>
option.</p>
<p>So, to summarize, a mode <em>must</em> provide
a <code>token</code> method, and it <em>may</em>
provide <code>startState</code>, <code>copyState</code>,
<code>compareStates</code>, and <code>indent</code> methods. For
an example of a trivial mode, see
the <a href="../mode/diff/diff.js">diff mode</a>, for a more involved
example, see the <a href="../mode/clike/clike.js">C-like
mode</a>.</p>
<p>Sometimes, it is useful for modes to <em>nest</em>—to have one
mode delegate work to another mode. An example of this kind of
mode is the <a href="../mode/htmlmixed/htmlmixed.js">mixed-mode HTML
mode</a>. To implement such nesting, it is usually necessary to
create mode objects and copy states yourself. To create a mode
object, there are <code>CodeMirror.getMode(options,
parserConfig)</code>, where the first argument is a configuration
object as passed to the mode constructor function, and the second
argument is a mode specification as in
the <a href="#option_mode"><code>mode</code></a> option. To copy a
state object, call <code>CodeMirror.copyState(mode, state)</code>,
where <code>mode</code> is the mode that created the given
state.</p>
<p id="innerMode">In a nested mode, it is recommended to add an
extra methods, <code>innerMode</code> which, given a state object,
returns a <code>{state, mode}</code> object with the inner mode
and its state for the current position. These are used by utility
scripts such as the <a href="#util_formatting">autoformatter</a>
and the <a href="#util_closetag">tag closer</a> to get context
information. Use the <code>CodeMirror.innerMode</code> helper
function to, starting from a mode and a state, recursively walk
down to the innermost mode and state.</p>
<p>To make indentation work properly in a nested parser, it is
advisable to give the <code>startState</code> method of modes that
are intended to be nested an optional argument that provides the
base indentation for the block of code. The JavaScript and CSS
parser do this, for example, to allow JavaScript and CSS code
inside the mixed-mode HTML mode to be properly indented.</p>
<p>Finally, it is possible to associate your mode, or a certain
configuration of your mode, with
a <a href="http://en.wikipedia.org/wiki/MIME">MIME</a> type. For
example, the JavaScript mode associates itself
with <code>text/javascript</code>, and its JSON variant
with <code>application/json</code>. To do this,
call <code>CodeMirror.defineMIME(mime, modeSpec)</code>,
where <code>modeSpec</code> can be a string or object specifying a
mode, as in the <a href="#option_mode"><code>mode</code></a>
option.</p>
<p id="extendMode">Sometimes, it is useful to add or override mode
object properties from external code.
The <code>CodeMirror.extendMode</code> can be used to add
properties to mode objects produced for a specific mode. Its first
argument is the name of the mode, its second an object that
specifies the properties that should be added. This is mostly
useful to add utilities that can later be looked
up <a href="#getMode"><code>getMode</code></a>.</p>
</div><div class="rightsmall blk">
<h2>Contents</h2>
<ul>
<li><a href="#overview">Overview</a></li>
<li><a href="#usage">Basic Usage</a></li>
<li><a href="#config">Configuration</a></li>
<li><a href="#keymaps">Keymaps</a></li>
<li><a href="#styling">Customized Styling</a></li>
<li><a href="#api">Programming API</a></li>
<li><a href="#addons">Add-ons</a></li>
<li><a href="#modeapi">Writing CodeMirror Modes</a></li>
</ul>
</div></div>
<div style="height: 2em">&nbsp;</div>
</body>
</html>
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>CodeMirror</title>
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Droid+Sans|Droid+Sans:bold"/>
<link rel="stylesheet" type="text/css" href="docs.css"/>
<link rel="alternate" href="http://twitter.com/statuses/user_timeline/242283288.rss" type="application/rss+xml"/>
</head>
<body>
<h1><span class="logo-braces">{ }</span> <a href="http://codemirror.net/">CodeMirror</a></h1>
<div class="grey">
<img src="baboon.png" class="logo" alt="logo"/>
<pre>
/* Old release
history */
</pre>
</div>
<p class="rel">27-02-2012: <a href="http://codemirror.net/codemirror-2.22.zip">Version 2.22</a>:</p>
<ul class="rel-note">
<li>Allow <a href="manual.html#keymaps">key handlers</a> to pass up events, allow binding characters.</li>
<li>Add <a href="manual.html#option_autoClearEmptyLines"><code>autoClearEmptyLines</code></a> option.</li>
<li>Properly use tab stops when rendering tabs.</li>
<li>Make PHP mode more robust.</li>
<li>Support indentation blocks in <a href="manual.html#util_foldcode">code folder</a>.</li>
<li>Add a script for <a href="manual.html#util_match-highlighter">highlighting instances of the selection</a>.</li>
<li>New <a href="../mode/properties/index.html">.properties</a> mode.</li>
<li>Fix many bugs.</li>
</ul>
<p class="rel">27-01-2012: <a href="http://codemirror.net/codemirror-2.21.zip">Version 2.21</a>:</p>
<ul class="rel-note">
<li>Added <a href="../mode/less/index.html">LESS</a>, <a href="../mode/mysql/index.html">MySQL</a>,
<a href="../mode/go/index.html">Go</a>, and <a href="../mode/verilog/index.html">Verilog</a> modes.</li>
<li>Add <a href="manual.html#option_smartIndent"><code>smartIndent</code></a>
option.</li>
<li>Support a cursor in <a href="manual.html#option_readOnly"><code>readOnly</code></a>-mode.</li>
<li>Support assigning multiple styles to a token.</li>
<li>Use a new approach to drawing the selection.</li>
<li>Add <a href="manual.html#scrollTo"><code>scrollTo</code></a> method.</li>
<li>Allow undo/redo events to span non-adjacent lines.</li>
<li>Lots and lots of bugfixes.</li>
</ul>
<p class="rel">20-12-2011: <a href="http://codemirror.net/codemirror-2.2.zip">Version 2.2</a>:</p>
<ul class="rel-note">
<li>Slightly incompatible API changes. Read <a href="upgrade_v2.2.html">this</a>.</li>
<li>New approach
to <a href="manual.html#option_extraKeys">binding</a> keys,
support for <a href="manual.html#option_keyMap">custom
bindings</a>.</li>
<li>Support for overwrite (insert).</li>
<li><a href="manual.html#option_tabSize">Custom-width</a>
and <a href="../demo/visibletabs.html">stylable</a> tabs.</li>
<li>Moved more code into <a href="manual.html#addons">add-on scripts</a>.</li>
<li>Support for sane vertical cursor movement in wrapped lines.</li>
<li>More reliable handling of
editing <a href="manual.html#markText">marked text</a>.</li>
<li>Add minimal <a href="../demo/emacs.html">emacs</a>
and <a href="../demo/vim.html">vim</a> bindings.</li>
<li>Rename <code>coordsFromIndex</code>
to <a href="manual.html#posFromIndex"><code>posFromIndex</code></a>,
add <a href="manual.html#indexFromPos"><code>indexFromPos</code></a>
method.</li>
</ul>
<p class="rel">21-11-2011: <a href="http://codemirror.net/codemirror-2.18.zip">Version 2.18</a>:</p>
<p class="rel-note">Fixes <code>TextMarker.clear</code>, which is broken in 2.17.</p>
<p class="rel">21-11-2011: <a href="http://codemirror.net/codemirror-2.17.zip">Version 2.17</a>:</p>
<ul class="rel-note">
<li>Add support for <a href="manual.html#option_lineWrapping">line
wrapping</a> and <a href="manual.html#hideLine">code
folding</a>.</li>
<li>Add <a href="../mode/gfm/index.html">Github-style Markdown</a> mode.</li>
<li>Add <a href="../theme/monokai.css">Monokai</a>
and <a href="../theme/rubyblue.css">Rubyblue</a> themes.</li>
<li>Add <a href="manual.html#setBookmark"><code>setBookmark</code></a> method.</li>
<li>Move some of the demo code into reusable components
under <a href="../lib/util/"><code>lib/util</code></a>.</li>
<li>Make screen-coord-finding code faster and more reliable.</li>
<li>Fix drag-and-drop in Firefox.</li>
<li>Improve support for IME.</li>
<li>Speed up content rendering.</li>
<li>Fix browser's built-in search in Webkit.</li>
<li>Make double- and triple-click work in IE.</li>
<li>Various fixes to modes.</li>
</ul>
<p class="rel">27-10-2011: <a href="http://codemirror.net/codemirror-2.16.zip">Version 2.16</a>:</p>
<ul class="rel-note">
<li>Add <a href="../mode/perl/index.html">Perl</a>, <a href="../mode/rust/index.html">Rust</a>, <a href="../mode/tiddlywiki/index.html">TiddlyWiki</a>, and <a href="../mode/groovy/index.html">Groovy</a> modes.</li>
<li>Dragging text inside the editor now moves, rather than copies.</li>
<li>Add a <a href="manual.html#coordsFromIndex"><code>coordsFromIndex</code></a> method.</li>
<li><strong>API change</strong>: <code>setValue</code> now no longer clears history. Use <a href="manual.html#clearHistory"><code>clearHistory</code></a> for that.</li>
<li><strong>API change</strong>: <a href="manual.html#markText"><code>markText</code></a> now
returns an object with <code>clear</code> and <code>find</code>
methods. Marked text is now more robust when edited.</li>
<li>Fix editing code with tabs in Internet Explorer.</li>
</ul>
<p class="rel">26-09-2011: <a href="http://codemirror.net/codemirror-2.15.zip">Version 2.15</a>:</p>
<p class="rel-note">Fix bug that snuck into 2.14: Clicking the
character that currently has the cursor didn't re-focus the
editor.</p>
<p class="rel">26-09-2011: <a href="http://codemirror.net/codemirror-2.14.zip">Version 2.14</a>:</p>
<ul class="rel-note">
<li>Add <a href="../mode/clojure/index.html">Clojure</a>, <a href="../mode/pascal/index.html">Pascal</a>, <a href="../mode/ntriples/index.html">NTriples</a>, <a href="../mode/jinja2/index.html">Jinja2</a>, and <a href="../mode/markdown/index.html">Markdown</a> modes.</li>
<li>Add <a href="../theme/cobalt.css">Cobalt</a> and <a href="../theme/eclipse.css">Eclipse</a> themes.</li>
<li>Add a <a href="manual.html#option_fixedGutter"><code>fixedGutter</code></a> option.</li>
<li>Fix bug with <code>setValue</code> breaking cursor movement.</li>
<li>Make gutter updates much more efficient.</li>
<li>Allow dragging of text out of the editor (on modern browsers).</li>
</ul>
<p class="rel">23-08-2011: <a href="http://codemirror.net/codemirror-2.13.zip">Version 2.13</a>:</p>
<ul class="rel-note">
<li>Add <a href="../mode/ruby/index.html">Ruby</a>, <a href="../mode/r/index.html">R</a>, <a href="../mode/coffeescript/index.html">CoffeeScript</a>, and <a href="../mode/velocity/index.html">Velocity</a> modes.</li>
<li>Add <a href="manual.html#getGutterElement"><code>getGutterElement</code></a> to API.</li>
<li>Several fixes to scrolling and positioning.</li>
<li>Add <a href="manual.html#option_smartHome"><code>smartHome</code></a> option.</li>
<li>Add an experimental <a href="../mode/xmlpure/index.html">pure XML</a> mode.</li>
</ul>
<p class="rel">25-07-2011: <a href="http://codemirror.net/codemirror-2.12.zip">Version 2.12</a>:</p>
<ul class="rel-note">
<li>Add a <a href="../mode/sparql/index.html">SPARQL</a> mode.</li>
<li>Fix bug with cursor jumping around in an unfocused editor in IE.</li>
<li>Allow key and mouse events to bubble out of the editor. Ignore widget clicks.</li>
<li>Solve cursor flakiness after undo/redo.</li>
<li>Fix block-reindent ignoring the last few lines.</li>
<li>Fix parsing of multi-line attrs in XML mode.</li>
<li>Use <code>innerHTML</code> for HTML-escaping.</li>
<li>Some fixes to indentation in C-like mode.</li>
<li>Shrink horiz scrollbars when long lines removed.</li>
<li>Fix width feedback loop bug that caused the width of an inner DIV to shrink.</li>
</ul>
<p class="rel">04-07-2011: <a href="http://codemirror.net/codemirror-2.11.zip">Version 2.11</a>:</p>
<ul class="rel-note">
<li>Add a <a href="../mode/scheme/index.html">Scheme mode</a>.</li>
<li>Add a <code>replace</code> method to search cursors, for cursor-preserving replacements.</li>
<li>Make the <a href="../mode/clike/index.html">C-like mode</a> mode more customizable.</li>
<li>Update XML mode to spot mismatched tags.</li>
<li>Add <code>getStateAfter</code> API and <code>compareState</code> mode API methods for finer-grained mode magic.</li>
<li>Add a <code>getScrollerElement</code> API method to manipulate the scrolling DIV.</li>
<li>Fix drag-and-drop for Firefox.</li>
<li>Add a C# configuration for the <a href="../mode/clike/index.html">C-like mode</a>.</li>
<li>Add <a href="../demo/fullscreen.html">full-screen editing</a> and <a href="../demo/changemode.html">mode-changing</a> demos.</li>
</ul>
<p class="rel">07-06-2011: <a href="http://codemirror.net/codemirror-2.1.zip">Version 2.1</a>:</p>
<p class="rel-note">Add
a <a href="manual.html#option_theme">theme</a> system
(<a href="../demo/theme.html">demo</a>). Note that this is not
backwards-compatible—you'll have to update your styles and
modes!</p>
<p class="rel">07-06-2011: <a href="http://codemirror.net/codemirror-2.02.zip">Version 2.02</a>:</p>
<ul class="rel-note">
<li>Add a <a href="../mode/lua/index.html">Lua mode</a>.</li>
<li>Fix reverse-searching for a regexp.</li>
<li>Empty lines can no longer break highlighting.</li>
<li>Rework scrolling model (the outer wrapper no longer does the scrolling).</li>
<li>Solve horizontal jittering on long lines.</li>
<li>Add <a href="../demo/runmode.html">runmode.js</a>.</li>
<li>Immediately re-highlight text when typing.</li>
<li>Fix problem with 'sticking' horizontal scrollbar.</li>
</ul>
<p class="rel">26-05-2011: <a href="http://codemirror.net/codemirror-2.01.zip">Version 2.01</a>:</p>
<ul class="rel-note">
<li>Add a <a href="../mode/smalltalk/index.html">Smalltalk mode</a>.</li>
<li>Add a <a href="../mode/rst/index.html">reStructuredText mode</a>.</li>
<li>Add a <a href="../mode/python/index.html">Python mode</a>.</li>
<li>Add a <a href="../mode/plsql/index.html">PL/SQL mode</a>.</li>
<li><code>coordsChar</code> now works</li>
<li>Fix a problem where <code>onCursorActivity</code> interfered with <code>onChange</code>.</li>
<li>Fix a number of scrolling and mouse-click-position glitches.</li>
<li>Pass information about the changed lines to <code>onChange</code>.</li>
<li>Support cmd-up/down on OS X.</li>
<li>Add triple-click line selection.</li>
<li>Don't handle shift when changing the selection through the API.</li>
<li>Support <code>"nocursor"</code> mode for <code>readOnly</code> option.</li>
<li>Add an <code>onHighlightComplete</code> option.</li>
<li>Fix the context menu for Firefox.</li>
</ul>
<p class="rel">28-03-2011: <a href="http://codemirror.net/codemirror-2.0.zip">Version 2.0</a>:</p>
<p class="rel-note">CodeMirror 2 is a complete rewrite that's
faster, smaller, simpler to use, and less dependent on browser
quirks. See <a href="internals.html">this</a>
and <a href="http://groups.google.com/group/codemirror/browse_thread/thread/5a8e894024a9f580">this</a>
for more information.</a>
<p class="rel">28-03-2011: <a href="http://codemirror.net/codemirror-1.0.zip">Version 1.0</a>:</p>
<ul class="rel-note">
<li>Fix error when debug history overflows.</li>
<li>Refine handling of C# verbatim strings.</li>
<li>Fix some issues with JavaScript indentation.</li>
</ul>
<p class="rel">22-02-2011: <a href="https://github.com/marijnh/codemirror/tree/beta2">Version 2.0 beta 2</a>:</p>
<p class="rel-note">Somewhat more mature API, lots of bugs shaken out.</a>
<p class="rel">17-02-2011: <a href="http://codemirror.net/codemirror-0.94.zip">Version 0.94</a>:</p>
<ul class="rel-note">
<li><code>tabMode: "spaces"</code> was modified slightly (now indents when something is selected).</li>
<li>Fixes a bug that would cause the selection code to break on some IE versions.</li>
<li>Disabling spell-check on WebKit browsers now works.</li>
</ul>
<p class="rel">08-02-2011: <a href="http://codemirror.net/">Version 2.0 beta 1</a>:</p>
<p class="rel-note">CodeMirror 2 is a complete rewrite of
CodeMirror, no longer depending on an editable frame.</p>
<p class="rel">19-01-2011: <a href="http://codemirror.net/codemirror-0.93.zip">Version 0.93</a>:</p>
<ul class="rel-note">
<li>Added a <a href="contrib/regex/index.html">Regular Expression</a> parser.</li>
<li>Fixes to the PHP parser.</li>
<li>Support for regular expression in search/replace.</li>
<li>Add <code>save</code> method to instances created with <code>fromTextArea</code>.</li>
<li>Add support for MS T-SQL in the SQL parser.</li>
<li>Support use of CSS classes for highlighting brackets.</li>
<li>Fix yet another hang with line-numbering in hidden editors.</li>
</ul>
<p class="rel">17-12-2010: <a href="http://codemirror.net/codemirror-0.92.zip">Version 0.92</a>:</p>
<ul class="rel-note">
<li>Make CodeMirror work in XHTML documents.</li>
<li>Fix bug in handling of backslashes in Python strings.</li>
<li>The <code>styleNumbers</code> option is now officially
supported and documented.</li>
<li><code>onLineNumberClick</code> option added.</li>
<li>More consistent names <code>onLoad</code> and
<code>onCursorActivity</code> callbacks. Old names still work, but
are deprecated.</li>
<li>Add a <a href="contrib/freemarker/index.html">Freemarker</a> mode.</li>
</ul>
<p class="rel">11-11-2010: <a
href="http://codemirror.net/codemirror-0.91.zip">Version 0.91</a>:</p>
<ul class="rel-note">
<li>Adds support for <a href="contrib/java">Java</a>.</li>
<li>Small additions to the <a href="contrib/php">PHP</a> and <a href="contrib/sql">SQL</a> parsers.</li>
<li>Work around various <a href="https://bugs.webkit.org/show_bug.cgi?id=47806">Webkit</a> <a href="https://bugs.webkit.org/show_bug.cgi?id=23474">issues</a>.</li>
<li>Fix <code>toTextArea</code> to update the code in the textarea.</li>
<li>Add a <code>noScriptCaching</code> option (hack to ease development).</li>
<li>Make sub-modes of <a href="mixedtest.html">HTML mixed</a> mode configurable.</li>
</ul>
<p class="rel">02-10-2010: <a
href="http://codemirror.net/codemirror-0.9.zip">Version 0.9</a>:</p>
<ul class="rel-note">
<li>Add support for searching backwards.</li>
<li>There are now parsers for <a href="contrib/scheme/index.html">Scheme</a>, <a href="contrib/xquery/index.html">XQuery</a>, and <a href="contrib/ometa/index.html">OmetaJS</a>.</li>
<li>Makes <code>height: "dynamic"</code> more robust.</li>
<li>Fixes bug where paste did not work on OS X.</li>
<li>Add a <code>enterMode</code> and <code>electricChars</code> options to make indentation even more customizable.</li>
<li>Add <code>firstLineNumber</code> option.</li>
<li>Fix bad handling of <code>@media</code> rules by the CSS parser.</li>
<li>Take a new, more robust approach to working around the invisible-last-line bug in WebKit.</li>
</ul>
<p class="rel">22-07-2010: <a
href="http://codemirror.net/codemirror-0.8.zip">Version 0.8</a>:</p>
<ul class="rel-note">
<li>Add a <code>cursorCoords</code> method to find the screen
coordinates of the cursor.</li>
<li>A number of fixes and support for more syntax in the PHP parser.</li>
<li>Fix indentation problem with JSON-mode JS parser in Webkit.</li>
<li>Add a <a href="compress.html">minification</a> UI.</li>
<li>Support a <code>height: dynamic</code> mode, where the editor's
height will adjust to the size of its content.</li>
<li>Better support for IME input mode.</li>
<li>Fix JavaScript parser getting confused when seeing a no-argument
function call.</li>
<li>Have CSS parser see the difference between selectors and other
identifiers.</li>
<li>Fix scrolling bug when pasting in a horizontally-scrolled
editor.</li>
<li>Support <code>toTextArea</code> method in instances created with
<code>fromTextArea</code>.</li>
<li>Work around new Opera cursor bug that causes the cursor to jump
when pressing backspace at the end of a line.</li>
</ul>
<p class="rel">27-04-2010: <a
href="http://codemirror.net/codemirror-0.67.zip">Version
0.67</a>:</p>
<p class="rel-note">More consistent page-up/page-down behaviour
across browsers. Fix some issues with hidden editors looping forever
when line-numbers were enabled. Make PHP parser parse
<code>"\\"</code> correctly. Have <code>jumpToLine</code> work on
line handles, and add <code>cursorLine</code> function to fetch the
line handle where the cursor currently is. Add new
<code>setStylesheet</code> function to switch style-sheets in a
running editor.</p>
<p class="rel">01-03-2010: <a
href="http://codemirror.net/codemirror-0.66.zip">Version
0.66</a>:</p>
<p class="rel-note">Adds <code>removeLine</code> method to API.
Introduces the <a href="contrib/plsql/index.html">PLSQL parser</a>.
Marks XML errors by adding (rather than replacing) a CSS class, so
that they can be disabled by modifying their style. Fixes several
selection bugs, and a number of small glitches.</p>
<p class="rel">12-11-2009: <a
href="http://codemirror.net/codemirror-0.65.zip">Version
0.65</a>:</p>
<p class="rel-note">Add support for having both line-wrapping and
line-numbers turned on, make paren-highlighting style customisable
(<code>markParen</code> and <code>unmarkParen</code> config
options), work around a selection bug that Opera
<em>re</em>introduced in version 10.</p>
<p class="rel">23-10-2009: <a
href="http://codemirror.net/codemirror-0.64.zip">Version
0.64</a>:</p>
<p class="rel-note">Solves some issues introduced by the
paste-handling changes from the previous release. Adds
<code>setSpellcheck</code>, <code>setTextWrapping</code>,
<code>setIndentUnit</code>, <code>setUndoDepth</code>,
<code>setTabMode</code>, and <code>setLineNumbers</code> to
customise a running editor. Introduces an <a
href="contrib/sql/index.html">SQL</a> parser. Fixes a few small
problems in the <a href="contrib/python/index.html">Python</a>
parser. And, as usual, add workarounds for various newly discovered
browser incompatibilities.</p>
<p class="rel"><em>31-08-2009</em>: <a
href="http://codemirror.net/codemirror-0.63.zip">Version
0.63</a>:</p>
<p class="rel-note"> Overhaul of paste-handling (less fragile), fixes for several
serious IE8 issues (cursor jumping, end-of-document bugs) and a number
of small problems.</p>
<p class="rel"><em>30-05-2009</em>: <a
href="http://codemirror.net/codemirror-0.62.zip">Version
0.62</a>:</p>
<p class="rel-note">Introduces <a href="contrib/python/index.html">Python</a>
and <a href="contrib/lua/index.html">Lua</a> parsers. Add
<code>setParser</code> (on-the-fly mode changing) and
<code>clearHistory</code> methods. Make parsing passes time-based
instead of lines-based (see the <code>passTime</code> option).</p>
</body></html>
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>CodeMirror: Real-world uses</title>
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Droid+Sans|Droid+Sans:bold"/>
<link rel="stylesheet" type="text/css" href="docs.css"/>
</head>
<body>
<h1><span class="logo-braces">{ }</span> <a href="http://codemirror.net/">CodeMirror</a></h1>
<div class="grey">
<img src="baboon.png" class="logo" alt="logo"/>
<pre>
/* Real world uses,
full list */
</pre>
</div>
<p><a href="mailto:marijnh@gmail.com">Contact me</a> if you'd like
your project to be added to this list.</p>
<ul>
<li><a href="http://brackets.io">Adobe Brackets</a> (code editor)</li>
<li><a href="http://bluegriffon.org/">BlueGriffon</a> (HTML editor)</li>
<li><a href="http://cargocollective.com/">Cargo Collective</a> (creative publishing platform)</li>
<li><a href="http://www.codebugapp.com/">Codebug</a> (PHP Xdebug front-end)</li>
<li><a href="http://code.google.com/p/codemirror2-gwt/">CodeMirror2-GWT</a> (Google Web Toolkit wrapper)</li>
<li><a href="http://codev.it/">Codev</a> (collaborative IDE)</li>
<li><a href="http://ot.substance.io/demo/">Collaborative CodeMirror demo</a> (CodeMirror + operational transforms)</li>
<li><a href="http://www.ckwnc.com/">CKWNC</a> (UML editor)</li>
<li><a href="http://cssdeck.com/">CSSDeck</a> (CSS showcase)</li>
<li><a href="http://ireneros.com/deck/deck.js-codemirror/introduction/#textarea-code">Deck.js integration</a> (slides with editors)</li>
<li><a href="http://www.dbninja.com">DbNinja</a> (MySQL access interface)</li>
<li><a href="http://elm-lang.org/Examples.elm">Elm language examples</a></li>
<li><a href="http://eloquentjavascript.net/chapter1.html">Eloquent JavaScript</a> (book)</li>
<li><a href="http://www.fastfig.com/">Fastfig</a> (online computation/math tool)</li>
<li><a href="http://blog.pamelafox.org/2012/02/interactive-html5-slides-with-fathomjs.html">FathomJS integration</a> (slides with editors, again)</li>
<li><a href="http://tour.golang.org">Go language tour</a></li>
<li><a href="https://github.com/github/android">GitHub's Android app</a></li>
<li><a href="https://script.google.com/">Google Apps Script</a></li>
<li><a href="http://try.haxe.org">Haxe</a> (Haxe Playground) </li>
<li><a href="http://megafonweblab.github.com/histone-javascript/">Histone template engine playground</a></li>
<li><a href="http://icecoder.net">ICEcoder</a> (web IDE)</li>
<li><a href="http://extensions.joomla.org/extensions/edition/editors/8723">Joomla plugin</a></li>
<li><a href="http://jsbin.com">jsbin.com</a> (JS playground)</li>
<li><a href="http://www.jshint.com/">JSHint</a> (JS linter)</li>
<li><a href="http://kl1p.com/cmtest/1">kl1p</a> (paste service)</li>
<li><a href="http://www.chris-granger.com/2012/04/12/light-table---a-new-ide-concept/">Light Table</a> (experimental IDE)</li>
<li><a href="http://www.mergely.com/">Mergely</a> (interactive diffing)</li>
<li><a href="https://notex.ch">NoTex</a> (rST authoring)</li>
<li><a href="https://github.com/mamacdon/orion-codemirror">Orion-CodeMirror integration</a> (running CodeMirror modes in Orion)</li>
<li><a href="http://paperjs.org/">Paper.js</a> (graphics scripting)</li>
<li><a href="http://prose.io/">Prose.io</a> (github content editor)</li>
<li><a href="http://ql.io/">ql.io</a> (http API query helper)</li>
<li><a href="http://qyapp.com">QiYun web app platform</a></li>
<li><a href="http://ariya.ofilabs.com/2011/09/hybrid-webnative-desktop-codemirror.html">Qt+Webkit integration</a> (building a desktop CodeMirror app)</li>
<li><a href="http://www.sketchpatch.net/labs/livecodelabIntro.html">sketchPatch Livecodelab</a></li>
<li><a href="http://www.skulpt.org/">Skulpt</a> (in-browser Python environment)</li.
<li><a href="http://www.solidshops.com/">SolidShops</a> (hosted e-commerce platform)</li>
<li><a href="http://sqlfiddle.com">SQLFiddle</a> (SQL playground)</li>
<li><a href="https://thefiletree.com">The File Tree</a> (collab editor)</li>
<li><a href="http://enjalot.com/tributary/2636296/sinwaves.js">Tributary</a> (augmented editing)</li>
<li><a href="http://webglplayground.net/">WebGL playground</a></li>
<li><a href="http://www.wescheme.org/">WeScheme</a> (learning tool)</li>
<li><a href="http://wordpress.org/extend/plugins/codemirror-for-codeeditor/">WordPress plugin</a></li>
<li><a href="http://media.chikuyonok.ru/codemirror2/">Zen Coding</a> (fast XML editing)</li>
</ul>
</body>
</html>
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>CodeMirror: Reporting Bugs</title>
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Droid+Sans|Droid+Sans:bold"/>
<link rel="stylesheet" type="text/css" href="docs.css"/>
<style>li { margin-top: 1em; }</style>
</head>
<body>
<h1><span class="logo-braces">{ }</span> <a href="http://codemirror.net/">CodeMirror</a></h1>
<div class="grey">
<img src="baboon.png" class="logo" alt="logo"/>
<pre>
/* Reporting bugs
effectively */
</pre>
</div>
<div class="left">
<p>So you found a problem in CodeMirror. By all means, report it! Bug
reports from users are the main drive behind improvements to
CodeMirror. But first, please read over these points:</p>
<ol>
<li>CodeMirror is maintained by volunteers. They don't owe you
anything, so be polite. Reports with an indignant or belligerent
tone tend to be moved to the bottom of the pile.</li>
<li>Include information about <strong>the browser in which the
problem occurred</strong>. Even if you tested several browsers, and
the problem occurred in all of them, mention this fact in the bug
report. Also include browser version numbers and the operating
system that you're on.</li>
<li>Mention which release of CodeMirror you're using. Preferably,
try also with the current development snapshot, to ensure the
problem has not already been fixed.</li>
<li>Mention very precisely what went wrong. "X is broken" is not a
good bug report. What did you expect to happen? What happened
instead? Describe the exact steps a maintainer has to take to make
the problem occur. We can not fix something that we can not
observe.</li>
<li>If the problem can not be reproduced in any of the demos
included in the CodeMirror distribution, please provide an HTML
document that demonstrates the problem. The best way to do this is
to go to <a href="http://jsbin.com/ihunin/edit">jsbin.com</a>, enter
it there, press save, and include the resulting link in your bug
report.</li>
</ol>
</div>
</body>
</html>
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>CodeMirror: Upgrading to v2.2</title>
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Droid+Sans|Droid+Sans:bold"/>
<link rel="stylesheet" type="text/css" href="docs.css"/>
</head>
<body>
<h1><span class="logo-braces">{ }</span> <a href="http://codemirror.net/">CodeMirror</a></h1>
<div class="grey">
<img src="baboon.png" class="logo" alt="logo"/>
<pre>
/* Upgrading to
v2.2 */
</pre>
</div>
<div class="left">
<p>There are a few things in the 2.2 release that require some care
when upgrading.</p>
<h2>No more default.css</h2>
<p>The default theme is now included
in <a href="../lib/codemirror.css"><code>codemirror.css</code></a>, so
you do not have to included it separately anymore. (It was tiny, so
even if you're not using it, the extra data overhead is negligible.)
<h2>Different key customization</h2>
<p>CodeMirror has moved to a system
where <a href="manual.html#option_keyMap">keymaps</a> are used to
bind behavior to keys. This means <a href="../demo/emacs.html">custom
bindings</a> are now possible.</p>
<p>Three options that influenced key
behavior, <code>tabMode</code>, <code>enterMode</code>,
and <code>smartHome</code>, are no longer supported. Instead, you can
provide custom bindings to influence the way these keys act. This is
done through the
new <a href="manual.html#option_extraKeys"><code>extraKeys</code></a>
option, which can hold an object mapping key names to functionality. A
simple example would be:</p>
<pre> extraKeys: {
"Ctrl-S": function(instance) { saveText(instance.getValue()); },
"Ctrl-/": "undo"
}</pre>
<p>Keys can be mapped either to functions, which will be given the
editor instance as argument, or to strings, which are mapped through
functions through the <code>CodeMirror.commands</code> table, which
contains all the built-in editing commands, and can be inspected and
extended by external code.</p>
<p>By default, the <code>Home</code> key is bound to
the <code>"goLineStartSmart"</code> command, which moves the cursor to
the first non-whitespace character on the line. You can set do this to
make it always go to the very start instead:</p>
<pre> extraKeys: {"Home": "goLineStart"}</pre>
<p>Similarly, <code>Enter</code> is bound
to <code>"newlineAndIndent"</code> by default. You can bind it to
something else to get different behavior. To disable special handling
completely and only get a newline character inserted, you can bind it
to <code>false</code>:</p>
<pre> extraKeys: {"Enter": false}</pre>
<p>The same works for <code>Tab</code>. If you don't want CodeMirror
to handle it, bind it to <code>false</code>. The default behaviour is
to indent the current line more (<code>"indentMore"</code> command),
and indent it less when shift is held (<code>"indentLess"</code>).
There are also <code>"indentAuto"</code> (smart indent)
and <code>"insertTab"</code> commands provided for alternate
behaviors. Or you can write your own handler function to do something
different altogether.</p>
<h2>Tabs</h2>
<p>Handling of tabs changed completely. The display width of tabs can
now be set with the <code>tabSize</code> option, and tabs can
be <a href="../demo/visibletabs.html">styled</a> by setting CSS rules
for the <code>cm-tab</code> class.</p>
<p>The default width for tabs is now 4, as opposed to the 8 that is
hard-wired into browsers. If you are relying on 8-space tabs, make
sure you explicitly set <code>tabSize: 8</code> in your options.</p>
</div>
</body>
</html>
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>CodeMirror</title>
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Droid+Sans|Droid+Sans:bold"/>
<link rel="stylesheet" type="text/css" href="doc/docs.css"/>
<link rel="alternate" href="http://twitter.com/statuses/user_timeline/242283288.rss" type="application/rss+xml"/>
</head>
<body>
<h1><span class="logo-braces">{ }</span> <a href="http://codemirror.net/">CodeMirror</a></h1>
<div class="grey">
<img src="doc/baboon.png" class="logo" alt="logo"/>
<pre>
/* In-browser code editing
made bearable */
</pre>
</div>
<div class="clear"><div class="left blk">
<p style="margin-top: 0">CodeMirror is a JavaScript component that
provides a code editor in the browser. When a mode is available for
the language you are coding in, it will color your code, and
optionally help with indentation.</p>
<p>A <a href="doc/manual.html">rich programming API</a> and a CSS
theming system are available for customizing CodeMirror to fit your
application, and extending it with new functionality.</p>
<div class="clear"><div class="left1 blk">
<h2 style="margin-top: 0">Supported modes:</h2>
<ul>
<li><a href="mode/clike/index.html">C, C++, C#</a></li>
<li><a href="mode/clojure/index.html">Clojure</a></li>
<li><a href="mode/coffeescript/index.html">CoffeeScript</a></li>
<li><a href="mode/commonlisp/index.html">Common Lisp</a></li>
<li><a href="mode/css/index.html">CSS</a></li>
<li><a href="mode/diff/index.html">diff</a></li>
<li><a href="mode/ecl/index.html">ECL</a></li>
<li><a href="mode/erlang/index.html">Erlang</a></li>
<li><a href="mode/go/index.html">Go</a></li>
<li><a href="mode/groovy/index.html">Groovy</a></li>
<li><a href="mode/haskell/index.html">Haskell</a></li>
<li><a href="mode/haxe/index.html">Haxe</a></li>
<li><a href="mode/htmlembedded/index.html">HTML embedded scripts</a></li>
<li><a href="mode/htmlmixed/index.html">HTML mixed-mode</a></li>
<li><a href="mode/clike/index.html">Java</a></li>
<li><a href="mode/javascript/index.html">JavaScript</a></li>
<li><a href="mode/jinja2/index.html">Jinja2</a></li>
<li><a href="mode/less/index.html">LESS</a></li>
<li><a href="mode/lua/index.html">Lua</a></li>
<li><a href="mode/markdown/index.html">Markdown</a> (<a href="mode/gfm/index.html">Github-flavour</a>)</li>
<li><a href="mode/mysql/index.html">MySQL</a></li>
<li><a href="mode/ntriples/index.html">NTriples</a></li>
<li><a href="mode/ocaml/index.html">OCaml</a></li>
<li><a href="mode/pascal/index.html">Pascal</a></li>
<li><a href="mode/perl/index.html">Perl</a></li>
<li><a href="mode/php/index.html">PHP</a></li>
<li><a href="mode/pig/index.html">Pig Latin</a></li>
<li><a href="mode/plsql/index.html">PL/SQL</a></li>
<li><a href="mode/properties/index.html">Properties files</a></li>
<li><a href="mode/python/index.html">Python</a></li>
<li><a href="mode/r/index.html">R</a></li>
<li>RPM <a href="mode/rpm/spec/index.html">spec</a> and <a href="mode/rpm/changes/index.html">changelog</a></li>
<li><a href="mode/rst/index.html">reStructuredText</a></li>
<li><a href="mode/ruby/index.html">Ruby</a></li>
<li><a href="mode/rust/index.html">Rust</a></li>
<li><a href="mode/clike/scala.html">Scala</a></li>
<li><a href="mode/scheme/index.html">Scheme</a></li>
<li><a href="mode/shell/index.html">Shell</a></li>
<li><a href="mode/sieve/index.html">Sieve</a></li>
<li><a href="mode/smalltalk/index.html">Smalltalk</a></li>
<li><a href="mode/smarty/index.html">Smarty</a></li>
<li><a href="mode/sparql/index.html">SPARQL</a></li>
<li><a href="mode/stex/index.html">sTeX, LaTeX</a></li>
<li><a href="mode/tiddlywiki/index.html">Tiddlywiki</a></li>
<li><a href="mode/tiki/index.html">Tiki wiki</a></li>
<li><a href="mode/vb/index.html">VB.NET</a></li>
<li><a href="mode/vbscript/index.html">VBScript</a></li>
<li><a href="mode/velocity/index.html">Velocity</a></li>
<li><a href="mode/verilog/index.html">Verilog</a></li>
<li><a href="mode/xml/index.html">XML/HTML</a></li>
<li><a href="mode/xquery/index.html">XQuery</a></li>
<li><a href="mode/yaml/index.html">YAML</a></li>
</ul>
</div><div class="left2 blk">
<h2 style="margin-top: 0">Usage demos:</h2>
<ul>
<li><a href="demo/complete.html">Autocompletion</a> (<a href="demo/xmlcomplete.html">XML</a>)</li>
<li><a href="demo/search.html">Search/replace</a></li>
<li><a href="demo/folding.html">Code folding</a></li>
<li><a href="demo/mustache.html">Mode overlays</a></li>
<li><a href="demo/multiplex.html">Mode multiplexer</a></li>
<li><a href="demo/preview.html">HTML editor with preview</a></li>
<li><a href="demo/resize.html">Auto-resizing editor</a></li>
<li><a href="demo/marker.html">Setting breakpoints</a></li>
<li><a href="demo/activeline.html">Highlighting the current line</a></li>
<li><a href="demo/matchhighlighter.html">Highlighting selection matches</a></li>
<li><a href="demo/theme.html">Theming</a></li>
<li><a href="demo/runmode.html">Stand-alone highlighting</a></li>
<li><a href="demo/fullscreen.html">Full-screen editing</a></li>
<li><a href="demo/changemode.html">Mode auto-changing</a></li>
<li><a href="demo/visibletabs.html">Visible tabs</a></li>
<li><a href="demo/formatting.html">Autoformatting of code</a></li>
<li><a href="demo/emacs.html">Emacs keybindings</a></li>
<li><a href="demo/vim.html">Vim keybindings</a></li>
<li><a href="demo/closetag.html">Automatic xml tag closing</a></li>
<li><a href="demo/loadmode.html">Lazy mode loading</a></li>
</ul>
<h2>Real-world uses:</h2>
<ul>
<li><a href="http://jsbin.com">jsbin.com</a> (JS playground)</li>
<li><a href="http://www.chris-granger.com/2012/04/12/light-table---a-new-ide-concept/">Light Table</a> (experimental IDE)</li>
<li><a href="http://brackets.io">Adobe Brackets</a> (code editor)</li>
<li><a href="http://www.mergely.com/">Mergely</a> (interactive diffing)</li>
<li><a href="https://script.google.com/">Google Apps Script</a></li>
<li><a href="https://github.com/github/android">GitHub's Android app</a></li>
<li><a href="http://eloquentjavascript.net/chapter1.html">Eloquent JavaScript</a> (book)</li>
<li><a href="http://media.chikuyonok.ru/codemirror2/">Zen Coding</a> (fast XML editing)</li>
<li><a href="http://paperjs.org/">Paper.js</a> (graphics scripting)</li>
<li><a href="http://tour.golang.org">Go language tour</a></li>
<li><a href="http://codev.it/">Codev</a> (collaborative IDE)</li>
<li><a href="http://enjalot.com/tributary/2636296/sinwaves.js">Tributary</a> (augmented editing)</li>
<li><a href="http://prose.io/">Prose.io</a> (github content editor)</li>
<li><a href="http://www.wescheme.org/">WeScheme</a> (learning tool)</li>
<li><a href="http://webglplayground.net/">WebGL playground</a></li>
<li><a href="http://ql.io/">ql.io</a> (http API query helper)</li>
<li><a href="http://elm-lang.org/Examples.elm">Elm language examples</a></li>
<li><a href="https://thefiletree.com">The File Tree</a> (collab editor)</li>
<li><a href="http://www.jshint.com/">JSHint</a> (JS linter)</li>
<li><a href="http://kl1p.com/cmtest/1">kl1p</a> (paste service)</li>
<li><a href="http://sqlfiddle.com">SQLFiddle</a> (SQL playground)</li>
<li><a href="http://try.haxe.org">Try Haxe</a> (Haxe Playground) </li>
<li><a href="http://cssdeck.com/">CSSDeck</a> (CSS showcase)</li>
<li><a href="http://www.sketchpatch.net/labs/livecodelabIntro.html">sketchPatch Livecodelab</a></li>
<li><a href="https://notex.ch">NoTex</a> (rST authoring)</li>
<li><a href="doc/realworld.html">More...</a></li>
</ul>
</div></div>
<h2 id="code">Getting the code</h2>
<p>All of CodeMirror is released under a <a
href="LICENSE">MIT-style</a> license. To get it, you can download
the <a href="http://codemirror.net/codemirror.zip">latest
release</a> or the current <a
href="http://codemirror.net/codemirror-latest.zip">development
snapshot</a> as zip files. To create a custom minified script file,
you can use the <a href="doc/compress.html">compression API</a>.</p>
<p>We use <a href="http://git-scm.com/">git</a> for version control.
The main repository can be fetched in this way:</p>
<pre class="code">git clone http://marijnhaverbeke.nl/git/codemirror</pre>
<p>CodeMirror can also be found on GitHub at <a
href="http://github.com/marijnh/CodeMirror">marijnh/CodeMirror</a>.
If you plan to hack on the code and contribute patches, the best way
to do it is to create a GitHub fork, and send pull requests.</p>
<h2 id="documention">Documentation</h2>
<p>The <a href="doc/manual.html">manual</a> is your first stop for
learning how to use this library. It starts with a quick explanation
of how to use the editor, and then describes the API in detail.</p>
<p>For those who want to learn more about the code, there is
an <a href="doc/internals.html">overview of the internals</a> available.
The <a href="http://github.com/marijnh/CodeMirror">source code</a>
itself is, for the most part, also well commented.</p>
<h2 id="support">Support and bug reports</h2>
<p>Community discussion, questions, and informal bug reporting is
done on
the <a href="http://groups.google.com/group/codemirror">CodeMirror
Google group</a>. There is a separate
group, <a href="http://groups.google.com/group/codemirror-announce">CodeMirror-announce</a>,
which is lower-volume, and is only used for major announcements—new
versions and such. These will be cross-posted to both groups, so you
don't need to subscribe to both.</p>
<p>Though bug reports through e-mail are responded to, the preferred
way to report bugs is to use
the <a href="http://github.com/marijnh/CodeMirror/issues">Github
issue tracker</a>. Before reporting a
bug, <a href="doc/reporting.html">read these pointers</a>. Also,
the issue tracker is for <em>bugs</em>, not requests for help.</p>
<p>When none of these seem fitting, you can
simply <a href="mailto:marijnh@gmail.com">e-mail the maintainer</a>
directly.</p>
<h2 id="supported">Supported browsers</h2>
<p>The following <em>desktop</em> browsers are able to run CodeMirror:</p>
<ul>
<li>Firefox 2 or higher</li>
<li>Chrome, any version</li>
<li>Safari 3 or higher</li>
<li>Opera 9 or higher (with some key-handling problems on OS X)</li>
<li>Internet Explorer 7 or higher in standards mode<br>
<em>(So not quirks mode. But quasi-standards mode with a
transitional doctype is also flaky. <code>&lt;!doctype
html></code> is recommended.)</em></li>
</ul>
<p>I am not actively testing against every new browser release, and
vendors have a habit of introducing bugs all the time, so I am
relying on the community to tell me when something breaks.
See <a href="#support">here</a> for information on how to contact
me.</p>
<p>Mobile browsers mostly kind of work, but, because of limitations
and their fundamentally different UI assumptions, show a lot of
quirks that are hard to work around.</p>
<h2 id="commercial">Commercial support</h2>
<p>CodeMirror is developed and maintained by me, Marijn Haverbeke,
in my own time. If your company is getting value out of CodeMirror,
please consider purchasing a support contract.</p>
<ul>
<li>You'll be funding further work on CodeMirror.</li>
<li>You ensure that you get a quick response when you have a
problem, even when I am otherwise busy.</li>
</ul>
<p>CodeMirror support contracts exist in two
forms—<strong>basic</strong> at €100 per month,
and <strong>premium</strong> at €500 per
month. <a href="mailto:marijnh@gmail.com">Contact me</a> for further
information.</p>
</div>
<div class="right blk">
<a href="http://codemirror.net/codemirror.zip" class="download">Download the latest release</a>
<h2>Support CodeMirror</h2>
<ul>
<li>Donate
(<span onclick="document.getElementById('paypal').submit();"
class="quasilink">Paypal</span>,
<span onclick="document.getElementById('bankinfo').style.display = 'block';"
class="quasilink">bank</span>, or
<a href="https://www.gittip.com/marijnh">Gittip</a>)</li>
<li>Purchase <a href="#commercial">commercial support</a></li>
</ul>
<p id="bankinfo" style="display: none;">
Bank: <i>Rabobank</i><br/>
Country: <i>Netherlands</i><br/>
SWIFT: <i>RABONL2U</i><br/>
Account: <i>147850770</i><br/>
Name: <i>Marijn Haverbeke</i><br/>
IBAN: <i>NL26 RABO 0147 8507 70</i>
</p>
<h2>Reading material</h2>
<ul>
<li><a href="doc/manual.html">User manual</a></li>
<li><a href="http://github.com/marijnh/CodeMirror">Browse the code</a></li>
</ul>
<h2 id=releases>Releases</h2>
<p class="rel">22-10-2012: <a href="http://codemirror.net/codemirror-2.35.zip">Version 2.35</a>:</p>
<ul class="rel-note">
<li>New (sub) mode: <a href="mode/javascript/typescript.html">TypeScript</a>.</li>
<li>Don't overwrite (insert key) when pasing.</li>
<li>Fix several bugs in <a href="doc/manual.html#markText"><code>markText</code></a>/undo interaction.</li>
<li>Better indentation of JavaScript code without semicolons.</li>
<li>Add <a href="doc/manual.html#defineInitHook"><code>defineInitHook</code></a> function.</li>
<li>Full <a href="https://github.com/marijnh/CodeMirror/compare/v2.34...v2.35">list of patches</a>.</li>
</ul>
<p class="rel">22-10-2012: <a href="http://codemirror.net/codemirror-3.0beta2.zip">Version 3.0, beta 2</a>:</p>
<p class="rel-note"><strong>BETA release, new major version</strong>. Only partially
backwards-compatible. See
the <a href="http://codemirror.net/3/doc/upgrade_v3.html">upgrading
guide</a> for more information. Changes since beta1:</p>
<ul class="rel-note">
<li>Fix page-based coordinate computation.</li>
<li>Fix firing of <a href="http://codemirror.net/3/doc/manual.html#event_gutterClick"><code>gutterClick</code></a> event.</li>
<li>Add <a href="http://codemirror.net/3/doc/manual.html#option_cursorHeight"><code>cursorHeight</code></a> option.</li>
<li>Fix bi-directional text regression.</li>
<li>Add <a href="http://codemirror.net/3/doc/manual.html#option_viewportMargin"><code>viewportMargin</code></a> option.</li>
<li>Directly handle mousewheel events (again, hopefully better).</li>
<li>Make vertical cursor movement more robust (through widgets, big line gaps).</li>
<li>Add <a href="http://codemirror.net/3/doc/manual.html#option_flattenSpans"><code>flattenSpans</code></a> option.</li>
<li>Initialization in hidden state works again.</li>
<li>Many optimizations. Poor responsiveness should be fixed.</li>
<li>Full <a href="https://github.com/marijnh/CodeMirror/compare/v3.0beta1...v3.0beta2">list of patches</a>.</li>
</ul>
<p class="rel">19-09-2012: <a href="http://codemirror.net/codemirror-2.34.zip">Version 2.34</a>:</p>
<ul class="rel-note">
<li>New mode: <a href="mode/commonlisp/index.html">Common Lisp</a>.</li>
<li>Fix right-click select-all on most browsers.</li>
<li>Change the way highlighting happens:<br>&nbsp; Saves memory and CPU cycles.<br>&nbsp; <code>compareStates</code> is no longer needed.<br>&nbsp; <code>onHighlightComplete</code> no longer works.</li>
<li>Integrate mode (Markdown, XQuery, CSS, sTex) tests in central testsuite.</li>
<li>Add a <a href="doc/manual.html#version"><code>CodeMirror.version</code></a> property.</li>
<li>More robust handling of nested modes in <a href="demo/formatting.html">formatting</a> and <a href="demo/closetag.html">closetag</a> plug-ins.</li>
<li>Un/redo now preserves <a href="doc/manual.html#markText">marked text</a> and bookmarks.</li>
<li><a href="https://github.com/marijnh/CodeMirror/compare/v2.33...v2.34">Full list</a> of patches.</li>
</ul>
<p class="rel">19-09-2012: <a href="http://codemirror.net/codemirror-3.0beta1.zip">Version 3.0, beta 1</a>:</p>
<p class="rel-note"><strong>BETA release, new major version</strong>. Only partially
backwards-compatible. See
the <a href="http://codemirror.net/3/doc/upgrade_v3.html">upgrading
guide</a> for more information. Major new features are:</p>
<ul class="rel-note">
<li>Bi-directional text support.</li>
<li>More powerful gutter model.</li>
<li>Support for arbitrary text/widget height.</li>
<li>In-line widgets.</li>
<li>Generalized event handling.</li>
</ul>
<p class="rel">23-08-2012: <a href="http://codemirror.net/codemirror-2.33.zip">Version 2.33</a>:</p>
<ul class="rel-note">
<li>New mode: <a href="mode/sieve/index.html">Sieve</a>.</li>
<li>New <a href="doc/manual.html#getViewport"><code>getViewPort</code></a> and <a href="doc/manual.html#option_onViewportChange"><code>onViewportChange</code></a> API.</li>
<li><a href="doc/manual.html#option_cursorBlinkRate">Configurable</a> cursor blink rate.</li>
<li>Make binding a key to <code>false</code> disabling handling (again).</li>
<li>Show non-printing characters as red dots.</li>
<li>More tweaks to the scrolling model.</li>
<li>Expanded testsuite. Basic linter added.</li>
<li>Remove most uses of <code>innerHTML</code>. Remove <code>CodeMirror.htmlEscape</code>.</li>
<li><a href="https://github.com/marijnh/CodeMirror/compare/v2.32...v2.33">Full list</a> of patches.</li>
</ul>
<p class="rel">23-07-2012: <a href="http://codemirror.net/codemirror-2.32.zip">Version 2.32</a>:</p>
<p class="rel-note">Emergency fix for a bug where an editor with
line wrapping on IE will break when there is <em>no</em>
scrollbar.</p>
<p class="rel">20-07-2012: <a href="http://codemirror.net/codemirror-2.31.zip">Version 2.31</a>:</p>
<ul class="rel-note">
<li>New modes: <a href="mode/ocaml/index.html">OCaml</a>, <a href="mode/haxe/index.html">Haxe</a>, and <a href="mode/vb/index.html">VB.NET</a>.</li>
<li>Several fixes to the new scrolling model.</li>
<li>Add a <a href="doc/manual.html#setSize"><code>setSize</code></a> method for programmatic resizing.</li>
<li>Add <a href="doc/manual.html#getHistory"><code>getHistory</code></a> and <a href="doc/manual.html#setHistory"><code>setHistory</code></a> methods.</li>
<li>Allow custom line separator string in <a href="doc/manual.html#getValue"><code>getValue</code></a> and <a href="doc/manual.html#getRange"><code>getRange</code></a>.</li>
<li>Support double- and triple-click drag, double-clicking whitespace.</li>
<li>And more... <a href="https://github.com/marijnh/CodeMirror/compare/v2.3...v2.31">(all patches)</a></li>
</ul>
<p class="rel">22-06-2012: <a href="http://codemirror.net/codemirror-2.3.zip">Version 2.3</a>:</p>
<ul class="rel-note">
<li><strong>New scrollbar implementation</strong>. Should flicker less. Changes DOM structure of the editor.</li>
<li>New theme: <a href="demo/theme.html?vibrant-ink">vibrant-ink</a>.</li>
<li>Many extensions to the VIM keymap (including text objects).</li>
<li>Add <a href="demo/multiplex.html">mode-multiplexing</a> utility script.</li>
<li>Fix bug where right-click paste works in read-only mode.</li>
<li>Add a <a href="doc/manual.html#getScrollInfo"><code>getScrollInfo</code></a> method.</li>
<li>Lots of other <a href="https://github.com/marijnh/CodeMirror/compare/v2.25...v2.3">fixes</a>.</li>
</ul>
<p class="rel">23-05-2012: <a href="http://codemirror.net/codemirror-2.25.zip">Version 2.25</a>:</p>
<ul class="rel-note">
<li>New mode: <a href="mode/erlang/index.html">Erlang</a>.</li>
<li><strong>Remove xmlpure mode</strong> (use <a href="mode/xml/index.html">xml.js</a>).</li>
<li>Fix line-wrapping in Opera.</li>
<li>Fix X Windows middle-click paste in Chrome.</li>
<li>Fix bug that broke pasting of huge documents.</li>
<li>Fix backspace and tab key repeat in Opera.</li>
</ul>
<p class="rel">23-04-2012: <a href="http://codemirror.net/codemirror-2.24.zip">Version 2.24</a>:</p>
<ul class="rel-note">
<li><strong>Drop support for Internet Explorer 6</strong>.</li>
<li>New
modes: <a href="mode/shell/index.html">Shell</a>, <a href="mode/tiki/index.html">Tiki
wiki</a>, <a href="mode/pig/index.html">Pig Latin</a>.</li>
<li>New themes: <a href="demo/theme.html?ambiance">Ambiance</a>, <a href="demo/theme.html?blackboard">Blackboard</a>.</li>
<li>More control over drag/drop
with <a href="doc/manual.html#option_dragDrop"><code>dragDrop</code></a>
and <a href="doc/manual.html#option_onDragEvent"><code>onDragEvent</code></a>
options.</li>
<li>Make HTML mode a bit less pedantic.</li>
<li>Add <a href="doc/manual.html#compoundChange"><code>compoundChange</code></a> API method.</li>
<li>Several fixes in undo history and line hiding.</li>
<li>Remove (broken) support for <code>catchall</code> in key maps,
add <code>nofallthrough</code> boolean field instead.</li>
</ul>
<p class="rel">26-03-2012: <a href="http://codemirror.net/codemirror-2.23.zip">Version 2.23</a>:</p>
<ul class="rel-note">
<li>Change <strong>default binding for tab</strong> <a href="javascript:void(document.getElementById('tabbinding').style.display='')">[more]</a>
<div style="display: none" id=tabbinding>
Starting in 2.23, these bindings are default:
<ul><li>Tab: Insert tab character</li>
<li>Shift-tab: Reset line indentation to default</li>
<li>Ctrl/Cmd-[: Reduce line indentation (old tab behaviour)</li>
<li>Ctrl/Cmd-]: Increase line indentation (old shift-tab behaviour)</li>
</ul>
</div>
</li>
<li>New modes: <a href="mode/xquery/index.html">XQuery</a> and <a href="mode/vbscript/index.html">VBScript</a>.</li>
<li>Two new themes: <a href="mode/less/index.html">lesser-dark</a> and <a href="mode/xquery/index.html">xq-dark</a>.</li>
<li>Differentiate between background and text styles in <a href="doc/manual.html#setLineClass"><code>setLineClass</code></a>.</li>
<li>Fix drag-and-drop in IE9+.</li>
<li>Extend <a href="doc/manual.html#charCoords"><code>charCoords</code></a>
and <a href="doc/manual.html#cursorCoords"><code>cursorCoords</code></a> with a <code>mode</code> argument.</li>
<li>Add <a href="doc/manual.html#option_autofocus"><code>autofocus</code></a> option.</li>
<li>Add <a href="doc/manual.html#findMarksAt"><code>findMarksAt</code></a> method.</li>
</ul>
<p><a href="doc/oldrelease.html">Older releases...</a></p>
</div></div>
<div style="height: 2em">&nbsp;</div>
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" id="paypal">
<input type="hidden" name="cmd" value="_s-xclick"/>
<input type="hidden" name="hosted_button_id" value="3FVHS5FGUY7CC"/>
</form>
</body>
</html>
// TODO number prefixes
(function() {
// Really primitive kill-ring implementation.
var killRing = [];
function addToRing(str) {
killRing.push(str);
if (killRing.length > 50) killRing.shift();
}
function getFromRing() { return killRing[killRing.length - 1] || ""; }
function popFromRing() { if (killRing.length > 1) killRing.pop(); return getFromRing(); }
CodeMirror.keyMap.emacs = {
"Ctrl-X": function(cm) {cm.setOption("keyMap", "emacs-Ctrl-X");},
"Ctrl-W": function(cm) {addToRing(cm.getSelection()); cm.replaceSelection("");},
"Ctrl-Alt-W": function(cm) {addToRing(cm.getSelection()); cm.replaceSelection("");},
"Alt-W": function(cm) {addToRing(cm.getSelection());},
"Ctrl-Y": function(cm) {cm.replaceSelection(getFromRing());},
"Alt-Y": function(cm) {cm.replaceSelection(popFromRing());},
"Ctrl-/": "undo", "Shift-Ctrl--": "undo", "Shift-Alt-,": "goDocStart", "Shift-Alt-.": "goDocEnd",
"Ctrl-S": "findNext", "Ctrl-R": "findPrev", "Ctrl-G": "clearSearch", "Shift-Alt-5": "replace",
"Ctrl-Z": "undo", "Cmd-Z": "undo", "Alt-/": "autocomplete",
fallthrough: ["basic", "emacsy"]
};
CodeMirror.keyMap["emacs-Ctrl-X"] = {
"Ctrl-S": "save", "Ctrl-W": "save", "S": "saveAll", "F": "open", "U": "undo", "K": "close",
auto: "emacs", nofallthrough: true
};
})();
// Supported keybindings:
//
// Cursor movement:
// h, j, k, l
// e, E, w, W, b, B
// Ctrl-f, Ctrl-b
// Ctrl-n, Ctrl-p
// $, ^, 0
// G
// ge, gE
// gg
// f<char>, F<char>, t<char>, T<char>
// Ctrl-o, Ctrl-i TODO (FIXME - Ctrl-O wont work in Chrome)
// /, ?, n, N TODO (does not work)
// #, * TODO
//
// Entering insert mode:
// i, I, a, A, o, O
// s
// ce, cb (without support for number of actions like c3e - TODO)
// cc
// S, C TODO
// cf<char>, cF<char>, ct<char>, cT<char>
//
// Deleting text:
// x, X
// J
// dd, D
// de, db (without support for number of actions like d3e - TODO)
// df<char>, dF<char>, dt<char>, dT<char>
//
// Yanking and pasting:
// yy, Y
// p, P
// p'<char> TODO - test
// y'<char> TODO - test
// m<char> TODO - test
//
// Changing text in place:
// ~
// r<char>
//
// Visual mode:
// v, V TODO
//
// Misc:
// . TODO
//
(function() {
var count = "";
var sdir = "f";
var buf = "";
var yank = 0;
var mark = [];
var reptTimes = 0;
function emptyBuffer() { buf = ""; }
function pushInBuffer(str) { buf += str; }
function pushCountDigit(digit) { return function(cm) {count += digit;}; }
function popCount() { var i = parseInt(count, 10); count = ""; return i || 1; }
function iterTimes(func) {
for (var i = 0, c = popCount(); i < c; ++i) func(i, i == c - 1);
}
function countTimes(func) {
if (typeof func == "string") func = CodeMirror.commands[func];
return function(cm) { iterTimes(function () { func(cm); }); };
}
function iterObj(o, f) {
for (var prop in o) if (o.hasOwnProperty(prop)) f(prop, o[prop]);
}
function iterList(l, f) {
for (var i = 0; i < l.length; ++i) f(l[i]);
}
function toLetter(ch) {
// T -> t, Shift-T -> T, '*' -> *, "Space" -> " "
if (ch.slice(0, 6) == "Shift-") {
return ch.slice(0, 1);
} else {
if (ch == "Space") return " ";
if (ch.length == 3 && ch[0] == "'" && ch[2] == "'") return ch[1];
return ch.toLowerCase();
}
}
var SPECIAL_SYMBOLS = "~`!@#$%^&*()_-+=[{}]\\|/?.,<>:;\"\'1234567890";
function toCombo(ch) {
// t -> T, T -> Shift-T, * -> '*', " " -> "Space"
if (ch == " ") return "Space";
var specialIdx = SPECIAL_SYMBOLS.indexOf(ch);
if (specialIdx != -1) return "'" + ch + "'";
if (ch.toLowerCase() == ch) return ch.toUpperCase();
return "Shift-" + ch.toUpperCase();
}
var word = [/\w/, /[^\w\s]/], bigWord = [/\S/];
function findWord(line, pos, dir, regexps) {
var stop = 0, next = -1;
if (dir > 0) { stop = line.length; next = 0; }
var start = stop, end = stop;
// Find bounds of next one.
outer: for (; pos != stop; pos += dir) {
for (var i = 0; i < regexps.length; ++i) {
if (regexps[i].test(line.charAt(pos + next))) {
start = pos;
for (; pos != stop; pos += dir) {
if (!regexps[i].test(line.charAt(pos + next))) break;
}
end = pos;
break outer;
}
}
}
return {from: Math.min(start, end), to: Math.max(start, end)};
}
function moveToWord(cm, regexps, dir, times, where) {
var cur = cm.getCursor();
for (var i = 0; i < times; i++) {
var line = cm.getLine(cur.line), startCh = cur.ch, word;
while (true) {
// If we're at start/end of line, start on prev/next respectivly
if (cur.ch == line.length && dir > 0) {
cur.line++;
cur.ch = 0;
line = cm.getLine(cur.line);
} else if (cur.ch == 0 && dir < 0) {
cur.line--;
cur.ch = line.length;
line = cm.getLine(cur.line);
}
if (!line) break;
// On to the actual searching
word = findWord(line, cur.ch, dir, regexps);
cur.ch = word[where == "end" ? "to" : "from"];
if (startCh == cur.ch && word.from != word.to) cur.ch = word[dir < 0 ? "from" : "to"];
else break;
}
}
return cur;
}
function joinLineNext(cm) {
var cur = cm.getCursor(), ch = cur.ch, line = cm.getLine(cur.line);
CodeMirror.commands.goLineEnd(cm);
if (cur.line != cm.lineCount()) {
CodeMirror.commands.goLineEnd(cm);
cm.replaceSelection(" ", "end");
CodeMirror.commands.delCharRight(cm);
}
}
function delTillMark(cm, cHar) {
var i = mark[cHar];
if (i === undefined) {
// console.log("Mark not set"); // TODO - show in status bar
return;
}
var l = cm.getCursor().line, start = i > l ? l : i, end = i > l ? i : l;
cm.setCursor(start);
for (var c = start; c <= end; c++) {
pushInBuffer("\n"+cm.getLine(start));
cm.removeLine(start);
}
}
function yankTillMark(cm, cHar) {
var i = mark[cHar];
if (i === undefined) {
// console.log("Mark not set"); // TODO - show in status bar
return;
}
var l = cm.getCursor().line, start = i > l ? l : i, end = i > l ? i : l;
for (var c = start; c <= end; c++) {
pushInBuffer("\n"+cm.getLine(c));
}
cm.setCursor(start);
}
function goLineStartText(cm) {
// Go to the start of the line where the text begins, or the end for whitespace-only lines
var cur = cm.getCursor(), firstNonWS = cm.getLine(cur.line).search(/\S/);
cm.setCursor(cur.line, firstNonWS == -1 ? line.length : firstNonWS, true);
}
function charIdxInLine(cm, cHar, motion_options) {
// Search for cHar in line.
// motion_options: {forward, inclusive}
// If inclusive = true, include it too.
// If forward = true, search forward, else search backwards.
// If char is not found on this line, do nothing
var cur = cm.getCursor(), line = cm.getLine(cur.line), idx;
var ch = toLetter(cHar), mo = motion_options;
if (mo.forward) {
idx = line.indexOf(ch, cur.ch + 1);
if (idx != -1 && mo.inclusive) idx += 1;
} else {
idx = line.lastIndexOf(ch, cur.ch);
if (idx != -1 && !mo.inclusive) idx += 1;
}
return idx;
}
function moveTillChar(cm, cHar, motion_options) {
// Move to cHar in line, as found by charIdxInLine.
var idx = charIdxInLine(cm, cHar, motion_options), cur = cm.getCursor();
if (idx != -1) cm.setCursor({line: cur.line, ch: idx});
}
function delTillChar(cm, cHar, motion_options) {
// delete text in this line, untill cHar is met,
// as found by charIdxInLine.
// If char is not found on this line, do nothing
var idx = charIdxInLine(cm, cHar, motion_options);
var cur = cm.getCursor();
if (idx !== -1) {
if (motion_options.forward) {
cm.replaceRange("", {line: cur.line, ch: cur.ch}, {line: cur.line, ch: idx});
} else {
cm.replaceRange("", {line: cur.line, ch: idx}, {line: cur.line, ch: cur.ch});
}
}
}
function enterInsertMode(cm) {
// enter insert mode: switch mode and cursor
popCount();
cm.setOption("keyMap", "vim-insert");
}
function dialog(cm, text, shortText, f) {
if (cm.openDialog) cm.openDialog(text, f);
else f(prompt(shortText, ""));
}
function showAlert(cm, text) {
var esc = text.replace(/[<&]/, function(ch) { return ch == "<" ? "&lt;" : "&amp;"; });
if (cm.openDialog) cm.openDialog(esc + " <button type=button>OK</button>");
else alert(text);
}
// main keymap
var map = CodeMirror.keyMap.vim = {
// Pipe (|); TODO: should be *screen* chars, so need a util function to turn tabs into spaces?
"'|'": function(cm) {
cm.setCursor(cm.getCursor().line, popCount() - 1, true);
},
"A": function(cm) {
cm.setCursor(cm.getCursor().line, cm.getCursor().ch+1, true);
enterInsertMode(cm);
},
"Shift-A": function(cm) { CodeMirror.commands.goLineEnd(cm); enterInsertMode(cm);},
"I": function(cm) { enterInsertMode(cm);},
"Shift-I": function(cm) { goLineStartText(cm); enterInsertMode(cm);},
"O": function(cm) {
CodeMirror.commands.goLineEnd(cm);
CodeMirror.commands.newlineAndIndent(cm);
enterInsertMode(cm);
},
"Shift-O": function(cm) {
CodeMirror.commands.goLineStart(cm);
cm.replaceSelection("\n", "start");
cm.indentLine(cm.getCursor().line);
enterInsertMode(cm);
},
"G": function(cm) { cm.setOption("keyMap", "vim-prefix-g");},
"Shift-D": function(cm) {
// commented out verions works, but I left original, cause maybe
// I don't know vim enouth to see what it does
/* var cur = cm.getCursor();
var f = {line: cur.line, ch: cur.ch}, t = {line: cur.line};
pushInBuffer(cm.getRange(f, t));
*/
emptyBuffer();
mark["Shift-D"] = cm.getCursor(false).line;
cm.setCursor(cm.getCursor(true).line);
delTillMark(cm,"Shift-D"); mark = [];
},
"S": function (cm) {
countTimes(function (_cm) {
CodeMirror.commands.delCharRight(_cm);
})(cm);
enterInsertMode(cm);
},
"M": function(cm) {cm.setOption("keyMap", "vim-prefix-m"); mark = [];},
"Y": function(cm) {cm.setOption("keyMap", "vim-prefix-y"); emptyBuffer(); yank = 0;},
"Shift-Y": function(cm) {
emptyBuffer();
mark["Shift-D"] = cm.getCursor(false).line;
cm.setCursor(cm.getCursor(true).line);
yankTillMark(cm,"Shift-D"); mark = [];
},
"/": function(cm) {var f = CodeMirror.commands.find; f && f(cm); sdir = "f";},
"'?'": function(cm) {
var f = CodeMirror.commands.find;
if (f) { f(cm); CodeMirror.commands.findPrev(cm); sdir = "r"; }
},
"N": function(cm) {
var fn = CodeMirror.commands.findNext;
if (fn) sdir != "r" ? fn(cm) : CodeMirror.commands.findPrev(cm);
},
"Shift-N": function(cm) {
var fn = CodeMirror.commands.findNext;
if (fn) sdir != "r" ? CodeMirror.commands.findPrev(cm) : fn.findNext(cm);
},
"Shift-G": function(cm) {
count == "" ? cm.setCursor(cm.lineCount()) : cm.setCursor(parseInt(count, 10)-1);
popCount();
CodeMirror.commands.goLineStart(cm);
},
"':'": function(cm) {
var exModeDialog = ': <input type="text" style="width: 90%"/>';
dialog(cm, exModeDialog, ':', function(command) {
if (command.match(/^\d+$/)) {
cm.setCursor(command - 1, cm.getCursor().ch);
} else {
showAlert(cm, "Bad command: " + command);
}
});
},
nofallthrough: true, style: "fat-cursor"
};
// standard mode switching
iterList(["d", "t", "T", "f", "F", "c", "r"], function (ch) {
CodeMirror.keyMap.vim[toCombo(ch)] = function (cm) {
cm.setOption("keyMap", "vim-prefix-" + ch);
emptyBuffer();
};
});
function addCountBindings(keyMap) {
// Add bindings for number keys
keyMap["0"] = function(cm) {
count.length > 0 ? pushCountDigit("0")(cm) : CodeMirror.commands.goLineStart(cm);
};
for (var i = 1; i < 10; ++i) keyMap[i] = pushCountDigit(i);
}
addCountBindings(CodeMirror.keyMap.vim);
// main num keymap
// Add bindings that are influenced by number keys
iterObj({
"Left": "goColumnLeft", "Right": "goColumnRight",
"Down": "goLineDown", "Up": "goLineUp", "Backspace": "goCharLeft",
"Space": "goCharRight",
"X": function(cm) {CodeMirror.commands.delCharRight(cm);},
"P": function(cm) {
var cur = cm.getCursor().line;
if (buf!= "") {
if (buf[0] == "\n") CodeMirror.commands.goLineEnd(cm);
cm.replaceRange(buf, cm.getCursor());
}
},
"Shift-X": function(cm) {CodeMirror.commands.delCharLeft(cm);},
"Shift-J": function(cm) {joinLineNext(cm);},
"Shift-P": function(cm) {
var cur = cm.getCursor().line;
if (buf!= "") {
CodeMirror.commands.goLineUp(cm);
CodeMirror.commands.goLineEnd(cm);
cm.replaceSelection(buf, "end");
}
cm.setCursor(cur+1);
},
"'~'": function(cm) {
var cur = cm.getCursor(), cHar = cm.getRange({line: cur.line, ch: cur.ch}, {line: cur.line, ch: cur.ch+1});
cHar = cHar != cHar.toLowerCase() ? cHar.toLowerCase() : cHar.toUpperCase();
cm.replaceRange(cHar, {line: cur.line, ch: cur.ch}, {line: cur.line, ch: cur.ch+1});
cm.setCursor(cur.line, cur.ch+1);
},
"Ctrl-B": function(cm) {CodeMirror.commands.goPageUp(cm);},
"Ctrl-F": function(cm) {CodeMirror.commands.goPageDown(cm);},
"Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
"U": "undo", "Ctrl-R": "redo"
}, function(key, cmd) { map[key] = countTimes(cmd); });
// empty key maps
iterList([
"vim-prefix-d'",
"vim-prefix-y'",
"vim-prefix-df",
"vim-prefix-dF",
"vim-prefix-dt",
"vim-prefix-dT",
"vim-prefix-c",
"vim-prefix-cf",
"vim-prefix-cF",
"vim-prefix-ct",
"vim-prefix-cT",
"vim-prefix-",
"vim-prefix-f",
"vim-prefix-F",
"vim-prefix-t",
"vim-prefix-T",
"vim-prefix-r",
"vim-prefix-m"
],
function (prefix) {
CodeMirror.keyMap[prefix] = {
auto: "vim",
nofallthrough: true,
style: "fat-cursor"
};
});
CodeMirror.keyMap["vim-prefix-g"] = {
"E": countTimes(function(cm) { cm.setCursor(moveToWord(cm, word, -1, 1, "start"));}),
"Shift-E": countTimes(function(cm) { cm.setCursor(moveToWord(cm, bigWord, -1, 1, "start"));}),
"G": function (cm) { cm.setCursor({line: 0, ch: cm.getCursor().ch});},
auto: "vim", nofallthrough: true, style: "fat-cursor"
};
CodeMirror.keyMap["vim-prefix-d"] = {
"D": countTimes(function(cm) {
pushInBuffer("\n"+cm.getLine(cm.getCursor().line));
cm.removeLine(cm.getCursor().line);
cm.setOption("keyMap", "vim");
}),
"'": function(cm) {
cm.setOption("keyMap", "vim-prefix-d'");
emptyBuffer();
},
"B": function(cm) {
var cur = cm.getCursor();
var line = cm.getLine(cur.line);
var index = line.lastIndexOf(" ", cur.ch);
pushInBuffer(line.substring(index, cur.ch));
cm.replaceRange("", {line: cur.line, ch: index}, cur);
cm.setOption("keyMap", "vim");
},
nofallthrough: true, style: "fat-cursor"
};
// FIXME - does not work for bindings like "d3e"
addCountBindings(CodeMirror.keyMap["vim-prefix-d"]);
CodeMirror.keyMap["vim-prefix-c"] = {
"B": function (cm) {
countTimes("delWordLeft")(cm);
enterInsertMode(cm);
},
"C": function (cm) {
iterTimes(function (i, last) {
CodeMirror.commands.deleteLine(cm);
if (i) {
CodeMirror.commands.delCharRight(cm);
if (last) CodeMirror.commands.deleteLine(cm);
}
});
enterInsertMode(cm);
},
nofallthrough: true, style: "fat-cursor"
};
iterList(["vim-prefix-d", "vim-prefix-c", "vim-prefix-"], function (prefix) {
iterList(["f", "F", "T", "t"],
function (ch) {
CodeMirror.keyMap[prefix][toCombo(ch)] = function (cm) {
cm.setOption("keyMap", prefix + ch);
emptyBuffer();
};
});
});
var MOTION_OPTIONS = {
"t": {inclusive: false, forward: true},
"f": {inclusive: true, forward: true},
"T": {inclusive: false, forward: false},
"F": {inclusive: true, forward: false}
};
function setupPrefixBindingForKey(m) {
CodeMirror.keyMap["vim-prefix-m"][m] = function(cm) {
mark[m] = cm.getCursor().line;
};
CodeMirror.keyMap["vim-prefix-d'"][m] = function(cm) {
delTillMark(cm,m);
};
CodeMirror.keyMap["vim-prefix-y'"][m] = function(cm) {
yankTillMark(cm,m);
};
CodeMirror.keyMap["vim-prefix-r"][m] = function (cm) {
var cur = cm.getCursor();
cm.replaceRange(toLetter(m),
{line: cur.line, ch: cur.ch},
{line: cur.line, ch: cur.ch + 1});
CodeMirror.commands.goColumnLeft(cm);
};
// all commands, related to motions till char in line
iterObj(MOTION_OPTIONS, function (ch, options) {
CodeMirror.keyMap["vim-prefix-" + ch][m] = function(cm) {
moveTillChar(cm, m, options);
};
CodeMirror.keyMap["vim-prefix-d" + ch][m] = function(cm) {
delTillChar(cm, m, options);
};
CodeMirror.keyMap["vim-prefix-c" + ch][m] = function(cm) {
delTillChar(cm, m, options);
enterInsertMode(cm);
};
});
}
for (var i = 65; i < 65 + 26; i++) { // uppercase alphabet char codes
var ch = String.fromCharCode(i);
setupPrefixBindingForKey(toCombo(ch));
setupPrefixBindingForKey(toCombo(ch.toLowerCase()));
}
for (var i = 0; i < SPECIAL_SYMBOLS.length; ++i) {
setupPrefixBindingForKey(toCombo(SPECIAL_SYMBOLS.charAt(i)));
}
setupPrefixBindingForKey("Space");
CodeMirror.keyMap["vim-prefix-y"] = {
"Y": countTimes(function(cm) {
pushInBuffer("\n"+cm.getLine(cm.getCursor().line+yank)); yank++;
cm.setOption("keyMap", "vim");
}),
"'": function(cm) {cm.setOption("keyMap", "vim-prefix-y'"); emptyBuffer();},
nofallthrough: true, style: "fat-cursor"
};
CodeMirror.keyMap["vim-insert"] = {
// TODO: override navigation keys so that Esc will cancel automatic indentation from o, O, i_<CR>
"Esc": function(cm) {
cm.setCursor(cm.getCursor().line, cm.getCursor().ch-1, true);
cm.setOption("keyMap", "vim");
},
"Ctrl-N": "autocomplete",
"Ctrl-P": "autocomplete",
fallthrough: ["default"]
};
function findMatchedSymbol(cm, cur, symb) {
var line = cur.line;
var symb = symb ? symb : cm.getLine(line)[cur.ch];
// Are we at the opening or closing char
var forwards = ['(', '[', '{'].indexOf(symb) != -1;
var reverseSymb = (function(sym) {
switch (sym) {
case '(' : return ')';
case '[' : return ']';
case '{' : return '}';
case ')' : return '(';
case ']' : return '[';
case '}' : return '{';
default : return null;
}
})(symb);
// Couldn't find a matching symbol, abort
if (reverseSymb == null) return cur;
// Tracking our imbalance in open/closing symbols. An opening symbol wii be
// the first thing we pick up if moving forward, this isn't true moving backwards
var disBal = forwards ? 0 : 1;
while (true) {
if (line == cur.line) {
// First pass, do some special stuff
var currLine = forwards ? cm.getLine(line).substr(cur.ch).split('') : cm.getLine(line).substr(0,cur.ch).split('').reverse();
} else {
var currLine = forwards ? cm.getLine(line).split('') : cm.getLine(line).split('').reverse();
}
for (var index = 0; index < currLine.length; index++) {
if (currLine[index] == symb) disBal++;
else if (currLine[index] == reverseSymb) disBal--;
if (disBal == 0) {
if (forwards && cur.line == line) return {line: line, ch: index + cur.ch};
else if (forwards) return {line: line, ch: index};
else return {line: line, ch: currLine.length - index - 1 };
}
}
if (forwards) line++;
else line--;
}
}
function selectCompanionObject(cm, revSymb, inclusive) {
var cur = cm.getCursor();
var end = findMatchedSymbol(cm, cur, revSymb);
var start = findMatchedSymbol(cm, end);
start.ch += inclusive ? 1 : 0;
end.ch += inclusive ? 0 : 1;
return {start: start, end: end};
}
// These are our motion commands to be used for navigation and selection with
// certian other commands. All should return a cursor object.
var motionList = ['B', 'E', 'J', 'K', 'H', 'L', 'W', 'Shift-W', "'^'", "'$'", "'%'", 'Esc'];
motions = {
'B': function(cm, times) { return moveToWord(cm, word, -1, times); },
'Shift-B': function(cm, times) { return moveToWord(cm, bigWord, -1, times); },
'E': function(cm, times) { return moveToWord(cm, word, 1, times, 'end'); },
'Shift-E': function(cm, times) { return moveToWord(cm, bigWord, 1, times, 'end'); },
'J': function(cm, times) {
var cur = cm.getCursor();
return {line: cur.line+times, ch : cur.ch};
},
'K': function(cm, times) {
var cur = cm.getCursor();
return {line: cur.line-times, ch: cur.ch};
},
'H': function(cm, times) {
var cur = cm.getCursor();
return {line: cur.line, ch: cur.ch-times};
},
'L': function(cm, times) {
var cur = cm.getCursor();
return {line: cur.line, ch: cur.ch+times};
},
'W': function(cm, times) { return moveToWord(cm, word, 1, times); },
'Shift-W': function(cm, times) { return moveToWord(cm, bigWord, 1, times); },
"'^'": function(cm, times) {
var cur = cm.getCursor();
var line = cm.getLine(cur.line).split('');
// Empty line :o
if (line.length == 0) return cur;
for (var index = 0; index < line.length; index++) {
if (line[index].match(/[^\s]/)) return {line: cur.line, ch: index};
}
},
"'$'": function(cm) {
var cur = cm.getCursor();
var line = cm.getLine(cur.line);
return {line: cur.line, ch: line.length};
},
"'%'": function(cm) { return findMatchedSymbol(cm, cm.getCursor()); },
"Esc" : function(cm) {
cm.setOption('vim');
reptTimes = 0;
return cm.getCursor();
}
};
// Map our movement actions each operator and non-operational movement
iterList(motionList, function(key, index, array) {
CodeMirror.keyMap['vim-prefix-d'][key] = function(cm) {
// Get our selected range
var start = cm.getCursor();
var end = motions[key](cm, reptTimes ? reptTimes : 1);
// Set swap var if range is of negative length
if ((start.line > end.line) || (start.line == end.line && start.ch > end.ch)) var swap = true;
// Take action, switching start and end if swap var is set
pushInBuffer(cm.getRange(swap ? end : start, swap ? start : end));
cm.replaceRange("", swap ? end : start, swap ? start : end);
// And clean up
reptTimes = 0;
cm.setOption("keyMap", "vim");
};
CodeMirror.keyMap['vim-prefix-c'][key] = function(cm) {
var start = cm.getCursor();
var end = motions[key](cm, reptTimes ? reptTimes : 1);
if ((start.line > end.line) || (start.line == end.line && start.ch > end.ch)) var swap = true;
pushInBuffer(cm.getRange(swap ? end : start, swap ? start : end));
cm.replaceRange("", swap ? end : start, swap ? start : end);
reptTimes = 0;
cm.setOption('keyMap', 'vim-insert');
};
CodeMirror.keyMap['vim-prefix-y'][key] = function(cm) {
var start = cm.getCursor();
var end = motions[key](cm, reptTimes ? reptTimes : 1);
if ((start.line > end.line) || (start.line == end.line && start.ch > end.ch)) var swap = true;
pushInBuffer(cm.getRange(swap ? end : start, swap ? start : end));
reptTimes = 0;
cm.setOption("keyMap", "vim");
};
CodeMirror.keyMap['vim'][key] = function(cm) {
var cur = motions[key](cm, reptTimes ? reptTimes : 1);
cm.setCursor(cur.line, cur.ch);
reptTimes = 0;
};
});
var nums = [1,2,3,4,5,6,7,8,9];
iterList(nums, function(key, index, array) {
CodeMirror.keyMap['vim'][key] = function (cm) {
reptTimes = (reptTimes * 10) + key;
};
CodeMirror.keyMap['vim-prefix-d'][key] = function (cm) {
reptTimes = (reptTimes * 10) + key;
};
CodeMirror.keyMap['vim-prefix-y'][key] = function (cm) {
reptTimes = (reptTimes * 10) + key;
};
CodeMirror.keyMap['vim-prefix-c'][key] = function (cm) {
reptTimes = (reptTimes * 10) + key;
};
});
// Create our keymaps for each operator and make xa and xi where x is an operator
// change to the corrosponding keymap
var operators = ['d', 'y', 'c'];
iterList(operators, function(key, index, array) {
CodeMirror.keyMap['vim-prefix-'+key+'a'] = {
auto: 'vim', nofallthrough: true, style: "fat-cursor"
};
CodeMirror.keyMap['vim-prefix-'+key+'i'] = {
auto: 'vim', nofallthrough: true, style: "fat-cursor"
};
CodeMirror.keyMap['vim-prefix-'+key]['A'] = function(cm) {
reptTimes = 0;
cm.setOption('keyMap', 'vim-prefix-' + key + 'a');
};
CodeMirror.keyMap['vim-prefix-'+key]['I'] = function(cm) {
reptTimes = 0;
cm.setOption('keyMap', 'vim-prefix-' + key + 'i');
};
});
function regexLastIndexOf(string, pattern, startIndex) {
for (var i = startIndex == null ? string.length : startIndex; i >= 0; --i)
if (pattern.test(string.charAt(i))) return i;
return -1;
}
// Create our text object functions. They work similar to motions but they
// return a start cursor as well
var textObjectList = ['W', 'Shift-[', 'Shift-9', '['];
var textObjects = {
'W': function(cm, inclusive) {
var cur = cm.getCursor();
var line = cm.getLine(cur.line);
var line_to_char = new String(line.substring(0, cur.ch));
var start = regexLastIndexOf(line_to_char, /[^a-zA-Z0-9]/) + 1;
var end = motions["E"](cm, 1) ;
end.ch += inclusive ? 1 : 0 ;
return {start: {line: cur.line, ch: start}, end: end };
},
'Shift-[': function(cm, inclusive) { return selectCompanionObject(cm, '}', inclusive); },
'Shift-9': function(cm, inclusive) { return selectCompanionObject(cm, ')', inclusive); },
'[': function(cm, inclusive) { return selectCompanionObject(cm, ']', inclusive); }
};
// One function to handle all operation upon text objects. Kinda funky but it works
// better than rewriting this code six times
function textObjectManipulation(cm, object, remove, insert, inclusive) {
// Object is the text object, delete object if remove is true, enter insert
// mode if insert is true, inclusive is the difference between a and i
var tmp = textObjects[object](cm, inclusive);
var start = tmp.start;
var end = tmp.end;
if ((start.line > end.line) || (start.line == end.line && start.ch > end.ch)) var swap = true ;
pushInBuffer(cm.getRange(swap ? end : start, swap ? start : end));
if (remove) cm.replaceRange("", swap ? end : start, swap ? start : end);
if (insert) cm.setOption('keyMap', 'vim-insert');
}
// And finally build the keymaps up from the text objects
for (var i = 0; i < textObjectList.length; ++i) {
var object = textObjectList[i];
(function(object) {
CodeMirror.keyMap['vim-prefix-di'][object] = function(cm) { textObjectManipulation(cm, object, true, false, false); };
CodeMirror.keyMap['vim-prefix-da'][object] = function(cm) { textObjectManipulation(cm, object, true, false, true); };
CodeMirror.keyMap['vim-prefix-yi'][object] = function(cm) { textObjectManipulation(cm, object, false, false, false); };
CodeMirror.keyMap['vim-prefix-ya'][object] = function(cm) { textObjectManipulation(cm, object, false, false, true); };
CodeMirror.keyMap['vim-prefix-ci'][object] = function(cm) { textObjectManipulation(cm, object, true, true, false); };
CodeMirror.keyMap['vim-prefix-ca'][object] = function(cm) { textObjectManipulation(cm, object, true, true, true); };
})(object)
}
})();
.CodeMirror {
line-height: 1em;
font-family: monospace;
/* Necessary so the scrollbar can be absolutely positioned within the wrapper on Lion. */
position: relative;
/* This prevents unwanted scrollbars from showing up on the body and wrapper in IE. */
overflow: hidden;
}
.CodeMirror-scroll {
overflow: auto;
height: 300px;
/* This is needed to prevent an IE[67] bug where the scrolled content
is visible outside of the scrolling box. */
position: relative;
outline: none;
}
/* Vertical scrollbar */
.CodeMirror-scrollbar {
position: absolute;
right: 0; top: 0;
overflow-x: hidden;
overflow-y: scroll;
z-index: 5;
}
.CodeMirror-scrollbar-inner {
/* This needs to have a nonzero width in order for the scrollbar to appear
in Firefox and IE9. */
width: 1px;
}
.CodeMirror-scrollbar.cm-sb-overlap {
/* Ensure that the scrollbar appears in Lion, and that it overlaps the content
rather than sitting to the right of it. */
position: absolute;
z-index: 1;
float: none;
right: 0;
min-width: 12px;
}
.CodeMirror-scrollbar.cm-sb-nonoverlap {
min-width: 12px;
}
.CodeMirror-scrollbar.cm-sb-ie7 {
min-width: 18px;
}
.CodeMirror-gutter {
position: absolute; left: 0; top: 0;
z-index: 10;
background-color: #f7f7f7;
border-right: 1px solid #eee;
min-width: 2em;
height: 100%;
}
.CodeMirror-gutter-text {
color: #aaa;
text-align: right;
padding: .4em .2em .4em .4em;
white-space: pre !important;
cursor: default;
}
.CodeMirror-lines {
padding: .4em;
white-space: pre;
cursor: text;
}
.CodeMirror pre {
-moz-border-radius: 0;
-webkit-border-radius: 0;
-o-border-radius: 0;
border-radius: 0;
border-width: 0; margin: 0; padding: 0; background: transparent;
font-family: inherit;
font-size: inherit;
padding: 0; margin: 0;
white-space: pre;
word-wrap: normal;
line-height: inherit;
color: inherit;
overflow: visible;
}
.CodeMirror-wrap pre {
word-wrap: break-word;
white-space: pre-wrap;
word-break: normal;
}
.CodeMirror-wrap .CodeMirror-scroll {
overflow-x: hidden;
}
.CodeMirror textarea {
outline: none !important;
}
.CodeMirror pre.CodeMirror-cursor {
z-index: 10;
position: absolute;
visibility: hidden;
border-left: 1px solid black;
border-right: none;
width: 0;
}
.cm-keymap-fat-cursor pre.CodeMirror-cursor {
width: auto;
border: 0;
background: transparent;
background: rgba(0, 200, 0, .4);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#6600c800, endColorstr=#4c00c800);
}
/* Kludge to turn off filter in ie9+, which also accepts rgba */
.cm-keymap-fat-cursor pre.CodeMirror-cursor:not(#nonsense_id) {
filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);
}
.CodeMirror pre.CodeMirror-cursor.CodeMirror-overwrite {}
.CodeMirror-focused pre.CodeMirror-cursor {
visibility: visible;
}
div.CodeMirror-selected { background: #d9d9d9; }
.CodeMirror-focused div.CodeMirror-selected { background: #d7d4f0; }
.CodeMirror-searching {
background: #ffa;
background: rgba(255, 255, 0, .4);
}
/* Default theme */
.cm-s-default span.cm-keyword {color: #708;}
.cm-s-default span.cm-atom {color: #219;}
.cm-s-default span.cm-number {color: #164;}
.cm-s-default span.cm-def {color: #00f;}
.cm-s-default span.cm-variable {color: black;}
.cm-s-default span.cm-variable-2 {color: #05a;}
.cm-s-default span.cm-variable-3 {color: #085;}
.cm-s-default span.cm-property {color: black;}
.cm-s-default span.cm-operator {color: black;}
.cm-s-default span.cm-comment {color: #a50;}
.cm-s-default span.cm-string {color: #a11;}
.cm-s-default span.cm-string-2 {color: #f50;}
.cm-s-default span.cm-meta {color: #555;}
.cm-s-default span.cm-error {color: #f00;}
.cm-s-default span.cm-qualifier {color: #555;}
.cm-s-default span.cm-builtin {color: #30a;}
.cm-s-default span.cm-bracket {color: #997;}
.cm-s-default span.cm-tag {color: #170;}
.cm-s-default span.cm-attribute {color: #00c;}
.cm-s-default span.cm-header {color: blue;}
.cm-s-default span.cm-quote {color: #090;}
.cm-s-default span.cm-hr {color: #999;}
.cm-s-default span.cm-link {color: #00c;}
span.cm-header, span.cm-strong {font-weight: bold;}
span.cm-em {font-style: italic;}
span.cm-emstrong {font-style: italic; font-weight: bold;}
span.cm-link {text-decoration: underline;}
span.cm-invalidchar {color: #f00;}
div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;}
div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;}
@media print {
/* Hide the cursor when printing */
.CodeMirror pre.CodeMirror-cursor {
visibility: hidden;
}
}
// CodeMirror version 2.35
//
// All functions that need access to the editor's state live inside
// the CodeMirror function. Below that, at the bottom of the file,
// some utilities are defined.
// CodeMirror is the only global var we claim
window.CodeMirror = (function() {
"use strict";
// This is the function that produces an editor instance. Its
// closure is used to store the editor state.
function CodeMirror(place, givenOptions) {
// Determine effective options based on given values and defaults.
var options = {}, defaults = CodeMirror.defaults;
for (var opt in defaults)
if (defaults.hasOwnProperty(opt))
options[opt] = (givenOptions && givenOptions.hasOwnProperty(opt) ? givenOptions : defaults)[opt];
var input = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em");
input.setAttribute("wrap", "off"); input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize", "off");
// Wraps and hides input textarea
var inputDiv = elt("div", [input], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
// The empty scrollbar content, used solely for managing the scrollbar thumb.
var scrollbarInner = elt("div", null, "CodeMirror-scrollbar-inner");
// The vertical scrollbar. Horizontal scrolling is handled by the scroller itself.
var scrollbar = elt("div", [scrollbarInner], "CodeMirror-scrollbar");
// DIVs containing the selection and the actual code
var lineDiv = elt("div"), selectionDiv = elt("div", null, null, "position: relative; z-index: -1");
// Blinky cursor, and element used to ensure cursor fits at the end of a line
var cursor = elt("pre", "\u00a0", "CodeMirror-cursor"), widthForcer = elt("pre", "\u00a0", "CodeMirror-cursor", "visibility: hidden");
// Used to measure text size
var measure = elt("div", null, null, "position: absolute; width: 100%; height: 0px; overflow: hidden; visibility: hidden;");
var lineSpace = elt("div", [measure, cursor, widthForcer, selectionDiv, lineDiv], null, "position: relative; z-index: 0");
var gutterText = elt("div", null, "CodeMirror-gutter-text"), gutter = elt("div", [gutterText], "CodeMirror-gutter");
// Moved around its parent to cover visible view
var mover = elt("div", [gutter, elt("div", [lineSpace], "CodeMirror-lines")], null, "position: relative");
// Set to the height of the text, causes scrolling
var sizer = elt("div", [mover], null, "position: relative");
// Provides scrolling
var scroller = elt("div", [sizer], "CodeMirror-scroll");
scroller.setAttribute("tabIndex", "-1");
// The element in which the editor lives.
var wrapper = elt("div", [inputDiv, scrollbar, scroller], "CodeMirror" + (options.lineWrapping ? " CodeMirror-wrap" : ""));
if (place.appendChild) place.appendChild(wrapper); else place(wrapper);
themeChanged(); keyMapChanged();
// Needed to hide big blue blinking cursor on Mobile Safari
if (ios) input.style.width = "0px";
if (!webkit) scroller.draggable = true;
lineSpace.style.outline = "none";
if (options.tabindex != null) input.tabIndex = options.tabindex;
if (options.autofocus) focusInput();
if (!options.gutter && !options.lineNumbers) gutter.style.display = "none";
// Needed to handle Tab key in KHTML
if (khtml) inputDiv.style.height = "1px", inputDiv.style.position = "absolute";
// Check for OS X >= 10.7. This has transparent scrollbars, so the
// overlaying of one scrollbar with another won't work. This is a
// temporary hack to simply turn off the overlay scrollbar. See
// issue #727.
if (mac_geLion) { scrollbar.style.zIndex = -2; scrollbar.style.visibility = "hidden"; }
// Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
else if (ie_lt8) scrollbar.style.minWidth = "18px";
// Delayed object wrap timeouts, making sure only one is active. blinker holds an interval.
var poll = new Delayed(), highlight = new Delayed(), blinker;
// mode holds a mode API object. doc is the tree of Line objects,
// frontier is the point up to which the content has been parsed,
// and history the undo history (instance of History constructor).
var mode, doc = new BranchChunk([new LeafChunk([new Line("")])]), frontier = 0, focused;
loadMode();
// The selection. These are always maintained to point at valid
// positions. Inverted is used to remember that the user is
// selecting bottom-to-top.
var sel = {from: {line: 0, ch: 0}, to: {line: 0, ch: 0}, inverted: false};
// Selection-related flags. shiftSelecting obviously tracks
// whether the user is holding shift.
var shiftSelecting, lastClick, lastDoubleClick, lastScrollTop = 0, draggingText,
overwrite = false, suppressEdits = false, pasteIncoming = false;
// Variables used by startOperation/endOperation to track what
// happened during the operation.
var updateInput, userSelChange, changes, textChanged, selectionChanged,
gutterDirty, callbacks;
// Current visible range (may be bigger than the view window).
var displayOffset = 0, showingFrom = 0, showingTo = 0, lastSizeC = 0;
// bracketHighlighted is used to remember that a bracket has been
// marked.
var bracketHighlighted;
// Tracks the maximum line length so that the horizontal scrollbar
// can be kept static when scrolling.
var maxLine = getLine(0), updateMaxLine = false, maxLineChanged = true;
var pollingFast = false; // Ensures slowPoll doesn't cancel fastPoll
var goalColumn = null;
// Initialize the content.
operation(function(){setValue(options.value || ""); updateInput = false;})();
var history = new History();
// Register our event handlers.
connect(scroller, "mousedown", operation(onMouseDown));
connect(scroller, "dblclick", operation(onDoubleClick));
connect(lineSpace, "selectstart", e_preventDefault);
// Gecko browsers fire contextmenu *after* opening the menu, at
// which point we can't mess with it anymore. Context menu is
// handled in onMouseDown for Gecko.
if (!gecko) connect(scroller, "contextmenu", onContextMenu);
connect(scroller, "scroll", onScrollMain);
connect(scrollbar, "scroll", onScrollBar);
connect(scrollbar, "mousedown", function() {if (focused) setTimeout(focusInput, 0);});
var resizeHandler = connect(window, "resize", function() {
if (wrapper.parentNode) updateDisplay(true);
else resizeHandler();
}, true);
connect(input, "keyup", operation(onKeyUp));
connect(input, "input", fastPoll);
connect(input, "keydown", operation(onKeyDown));
connect(input, "keypress", operation(onKeyPress));
connect(input, "focus", onFocus);
connect(input, "blur", onBlur);
function drag_(e) {
if (options.onDragEvent && options.onDragEvent(instance, addStop(e))) return;
e_stop(e);
}
if (options.dragDrop) {
connect(scroller, "dragstart", onDragStart);
connect(scroller, "dragenter", drag_);
connect(scroller, "dragover", drag_);
connect(scroller, "drop", operation(onDrop));
}
connect(scroller, "paste", function(){focusInput(); fastPoll();});
connect(input, "paste", function(){pasteIncoming = true; fastPoll();});
connect(input, "cut", operation(function(){
if (!options.readOnly) replaceSelection("");
}));
// Needed to handle Tab key in KHTML
if (khtml) connect(sizer, "mouseup", function() {
if (document.activeElement == input) input.blur();
focusInput();
});
// IE throws unspecified error in certain cases, when
// trying to access activeElement before onload
var hasFocus; try { hasFocus = (document.activeElement == input); } catch(e) { }
if (hasFocus || options.autofocus) setTimeout(onFocus, 20);
else onBlur();
function isLine(l) {return l >= 0 && l < doc.size;}
// The instance object that we'll return. Mostly calls out to
// local functions in the CodeMirror function. Some do some extra
// range checking and/or clipping. operation is used to wrap the
// call so that changes it makes are tracked, and the display is
// updated afterwards.
var instance = wrapper.CodeMirror = {
getValue: getValue,
setValue: operation(setValue),
getSelection: getSelection,
replaceSelection: operation(replaceSelection),
focus: function(){window.focus(); focusInput(); onFocus(); fastPoll();},
setOption: function(option, value) {
var oldVal = options[option];
options[option] = value;
if (option == "mode" || option == "indentUnit") loadMode();
else if (option == "readOnly" && value == "nocursor") {onBlur(); input.blur();}
else if (option == "readOnly" && !value) {resetInput(true);}
else if (option == "theme") themeChanged();
else if (option == "lineWrapping" && oldVal != value) operation(wrappingChanged)();
else if (option == "tabSize") updateDisplay(true);
else if (option == "keyMap") keyMapChanged();
else if (option == "tabindex") input.tabIndex = value;
if (option == "lineNumbers" || option == "gutter" || option == "firstLineNumber" ||
option == "theme" || option == "lineNumberFormatter") {
gutterChanged();
updateDisplay(true);
}
},
getOption: function(option) {return options[option];},
getMode: function() {return mode;},
undo: operation(undo),
redo: operation(redo),
indentLine: operation(function(n, dir) {
if (typeof dir != "string") {
if (dir == null) dir = options.smartIndent ? "smart" : "prev";
else dir = dir ? "add" : "subtract";
}
if (isLine(n)) indentLine(n, dir);
}),
indentSelection: operation(indentSelected),
historySize: function() {return {undo: history.done.length, redo: history.undone.length};},
clearHistory: function() {history = new History();},
setHistory: function(histData) {
history = new History();
history.done = histData.done;
history.undone = histData.undone;
},
getHistory: function() {
function cp(arr) {
for (var i = 0, nw = [], nwelt; i < arr.length; ++i) {
nw.push(nwelt = []);
for (var j = 0, elt = arr[i]; j < elt.length; ++j) {
var old = [], cur = elt[j];
nwelt.push({start: cur.start, added: cur.added, old: old});
for (var k = 0; k < cur.old.length; ++k) old.push(hlText(cur.old[k]));
}
}
return nw;
}
return {done: cp(history.done), undone: cp(history.undone)};
},
matchBrackets: operation(function(){matchBrackets(true);}),
getTokenAt: operation(function(pos) {
pos = clipPos(pos);
return getLine(pos.line).getTokenAt(mode, getStateBefore(pos.line), options.tabSize, pos.ch);
}),
getStateAfter: function(line) {
line = clipLine(line == null ? doc.size - 1: line);
return getStateBefore(line + 1);
},
cursorCoords: function(start, mode) {
if (start == null) start = sel.inverted;
return this.charCoords(start ? sel.from : sel.to, mode);
},
charCoords: function(pos, mode) {
pos = clipPos(pos);
if (mode == "local") return localCoords(pos, false);
if (mode == "div") return localCoords(pos, true);
return pageCoords(pos);
},
coordsChar: function(coords) {
var off = eltOffset(lineSpace);
return coordsChar(coords.x - off.left, coords.y - off.top);
},
markText: operation(markText),
setBookmark: setBookmark,
findMarksAt: findMarksAt,
setMarker: operation(addGutterMarker),
clearMarker: operation(removeGutterMarker),
setLineClass: operation(setLineClass),
hideLine: operation(function(h) {return setLineHidden(h, true);}),
showLine: operation(function(h) {return setLineHidden(h, false);}),
onDeleteLine: function(line, f) {
if (typeof line == "number") {
if (!isLine(line)) return null;
line = getLine(line);
}
(line.handlers || (line.handlers = [])).push(f);
return line;
},
lineInfo: lineInfo,
getViewport: function() { return {from: showingFrom, to: showingTo};},
addWidget: function(pos, node, scroll, vert, horiz) {
pos = localCoords(clipPos(pos));
var top = pos.yBot, left = pos.x;
node.style.position = "absolute";
sizer.appendChild(node);
if (vert == "over") top = pos.y;
else if (vert == "near") {
var vspace = Math.max(scroller.offsetHeight, doc.height * textHeight()),
hspace = Math.max(sizer.clientWidth, lineSpace.clientWidth) - paddingLeft();
if (pos.yBot + node.offsetHeight > vspace && pos.y > node.offsetHeight)
top = pos.y - node.offsetHeight;
if (left + node.offsetWidth > hspace)
left = hspace - node.offsetWidth;
}
node.style.top = (top + paddingTop()) + "px";
node.style.left = node.style.right = "";
if (horiz == "right") {
left = sizer.clientWidth - node.offsetWidth;
node.style.right = "0px";
} else {
if (horiz == "left") left = 0;
else if (horiz == "middle") left = (sizer.clientWidth - node.offsetWidth) / 2;
node.style.left = (left + paddingLeft()) + "px";
}
if (scroll)
scrollIntoView(left, top, left + node.offsetWidth, top + node.offsetHeight);
},
lineCount: function() {return doc.size;},
clipPos: clipPos,
getCursor: function(start) {
if (start == null) start = sel.inverted;
return copyPos(start ? sel.from : sel.to);
},
somethingSelected: function() {return !posEq(sel.from, sel.to);},
setCursor: operation(function(line, ch, user) {
if (ch == null && typeof line.line == "number") setCursor(line.line, line.ch, user);
else setCursor(line, ch, user);
}),
setSelection: operation(function(from, to, user) {
(user ? setSelectionUser : setSelection)(clipPos(from), clipPos(to || from));
}),
getLine: function(line) {if (isLine(line)) return getLine(line).text;},
getLineHandle: function(line) {if (isLine(line)) return getLine(line);},
setLine: operation(function(line, text) {
if (isLine(line)) replaceRange(text, {line: line, ch: 0}, {line: line, ch: getLine(line).text.length});
}),
removeLine: operation(function(line) {
if (isLine(line)) replaceRange("", {line: line, ch: 0}, clipPos({line: line+1, ch: 0}));
}),
replaceRange: operation(replaceRange),
getRange: function(from, to, lineSep) {return getRange(clipPos(from), clipPos(to), lineSep);},
triggerOnKeyDown: operation(onKeyDown),
execCommand: function(cmd) {return commands[cmd](instance);},
// Stuff used by commands, probably not much use to outside code.
moveH: operation(moveH),
deleteH: operation(deleteH),
moveV: operation(moveV),
toggleOverwrite: function() {
if(overwrite){
overwrite = false;
cursor.className = cursor.className.replace(" CodeMirror-overwrite", "");
} else {
overwrite = true;
cursor.className += " CodeMirror-overwrite";
}
},
posFromIndex: function(off) {
var lineNo = 0, ch;
doc.iter(0, doc.size, function(line) {
var sz = line.text.length + 1;
if (sz > off) { ch = off; return true; }
off -= sz;
++lineNo;
});
return clipPos({line: lineNo, ch: ch});
},
indexFromPos: function (coords) {
if (coords.line < 0 || coords.ch < 0) return 0;
var index = coords.ch;
doc.iter(0, coords.line, function (line) {
index += line.text.length + 1;
});
return index;
},
scrollTo: function(x, y) {
if (x != null) scroller.scrollLeft = x;
if (y != null) scrollbar.scrollTop = scroller.scrollTop = y;
updateDisplay([]);
},
getScrollInfo: function() {
return {x: scroller.scrollLeft, y: scrollbar.scrollTop,
height: scrollbar.scrollHeight, width: scroller.scrollWidth};
},
setSize: function(width, height) {
function interpret(val) {
val = String(val);
return /^\d+$/.test(val) ? val + "px" : val;
}
if (width != null) wrapper.style.width = interpret(width);
if (height != null) scroller.style.height = interpret(height);
instance.refresh();
},
operation: function(f){return operation(f)();},
compoundChange: function(f){return compoundChange(f);},
refresh: function(){
updateDisplay(true, null, lastScrollTop);
if (scrollbar.scrollHeight > lastScrollTop)
scrollbar.scrollTop = lastScrollTop;
},
getInputField: function(){return input;},
getWrapperElement: function(){return wrapper;},
getScrollerElement: function(){return scroller;},
getGutterElement: function(){return gutter;}
};
function getLine(n) { return getLineAt(doc, n); }
function updateLineHeight(line, height) {
gutterDirty = true;
var diff = height - line.height;
for (var n = line; n; n = n.parent) n.height += diff;
}
function lineContent(line, wrapAt) {
if (!line.styles)
line.highlight(mode, line.stateAfter = getStateBefore(lineNo(line)), options.tabSize);
return line.getContent(options.tabSize, wrapAt, options.lineWrapping);
}
function setValue(code) {
var top = {line: 0, ch: 0};
updateLines(top, {line: doc.size - 1, ch: getLine(doc.size-1).text.length},
splitLines(code), top, top);
updateInput = true;
}
function getValue(lineSep) {
var text = [];
doc.iter(0, doc.size, function(line) { text.push(line.text); });
return text.join(lineSep || "\n");
}
function onScrollBar(e) {
if (scrollbar.scrollTop != lastScrollTop) {
lastScrollTop = scroller.scrollTop = scrollbar.scrollTop;
updateDisplay([]);
}
}
function onScrollMain(e) {
if (options.fixedGutter && gutter.style.left != scroller.scrollLeft + "px")
gutter.style.left = scroller.scrollLeft + "px";
if (scroller.scrollTop != lastScrollTop) {
lastScrollTop = scroller.scrollTop;
if (scrollbar.scrollTop != lastScrollTop)
scrollbar.scrollTop = lastScrollTop;
updateDisplay([]);
}
if (options.onScroll) options.onScroll(instance);
}
function onMouseDown(e) {
setShift(e_prop(e, "shiftKey"));
// Check whether this is a click in a widget
for (var n = e_target(e); n != wrapper; n = n.parentNode)
if (n.parentNode == sizer && n != mover) return;
// See if this is a click in the gutter
for (var n = e_target(e); n != wrapper; n = n.parentNode)
if (n.parentNode == gutterText) {
if (options.onGutterClick)
options.onGutterClick(instance, indexOf(gutterText.childNodes, n) + showingFrom, e);
return e_preventDefault(e);
}
var start = posFromMouse(e);
switch (e_button(e)) {
case 3:
if (gecko) onContextMenu(e);
return;
case 2:
if (start) setCursor(start.line, start.ch, true);
setTimeout(focusInput, 20);
e_preventDefault(e);
return;
}
// For button 1, if it was clicked inside the editor
// (posFromMouse returning non-null), we have to adjust the
// selection.
if (!start) {if (e_target(e) == scroller) e_preventDefault(e); return;}
if (!focused) onFocus();
var now = +new Date, type = "single";
if (lastDoubleClick && lastDoubleClick.time > now - 400 && posEq(lastDoubleClick.pos, start)) {
type = "triple";
e_preventDefault(e);
setTimeout(focusInput, 20);
selectLine(start.line);
} else if (lastClick && lastClick.time > now - 400 && posEq(lastClick.pos, start)) {
type = "double";
lastDoubleClick = {time: now, pos: start};
e_preventDefault(e);
var word = findWordAt(start);
setSelectionUser(word.from, word.to);
} else { lastClick = {time: now, pos: start}; }
function dragEnd(e2) {
if (webkit) scroller.draggable = false;
draggingText = false;
up(); drop();
if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
e_preventDefault(e2);
setCursor(start.line, start.ch, true);
focusInput();
}
}
var last = start, going;
if (options.dragDrop && dragAndDrop && !options.readOnly && !posEq(sel.from, sel.to) &&
!posLess(start, sel.from) && !posLess(sel.to, start) && type == "single") {
// Let the drag handler handle this.
if (webkit) scroller.draggable = true;
var up = connect(document, "mouseup", operation(dragEnd), true);
var drop = connect(scroller, "drop", operation(dragEnd), true);
draggingText = true;
// IE's approach to draggable
if (scroller.dragDrop) scroller.dragDrop();
return;
}
e_preventDefault(e);
if (type == "single") setCursor(start.line, start.ch, true);
var startstart = sel.from, startend = sel.to;
function doSelect(cur) {
if (type == "single") {
setSelectionUser(start, cur);
} else if (type == "double") {
var word = findWordAt(cur);
if (posLess(cur, startstart)) setSelectionUser(word.from, startend);
else setSelectionUser(startstart, word.to);
} else if (type == "triple") {
if (posLess(cur, startstart)) setSelectionUser(startend, clipPos({line: cur.line, ch: 0}));
else setSelectionUser(startstart, clipPos({line: cur.line + 1, ch: 0}));
}
}
function extend(e) {
var cur = posFromMouse(e, true);
if (cur && !posEq(cur, last)) {
if (!focused) onFocus();
last = cur;
doSelect(cur);
updateInput = false;
var visible = visibleLines();
if (cur.line >= visible.to || cur.line < visible.from)
going = setTimeout(operation(function(){extend(e);}), 150);
}
}
function done(e) {
clearTimeout(going);
var cur = posFromMouse(e);
if (cur) doSelect(cur);
e_preventDefault(e);
focusInput();
updateInput = true;
move(); up();
}
var move = connect(document, "mousemove", operation(function(e) {
clearTimeout(going);
e_preventDefault(e);
if (!ie && !e_button(e)) done(e);
else extend(e);
}), true);
var up = connect(document, "mouseup", operation(done), true);
}
function onDoubleClick(e) {
for (var n = e_target(e); n != wrapper; n = n.parentNode)
if (n.parentNode == gutterText) return e_preventDefault(e);
e_preventDefault(e);
}
function onDrop(e) {
if (options.onDragEvent && options.onDragEvent(instance, addStop(e))) return;
e_preventDefault(e);
var pos = posFromMouse(e, true), files = e.dataTransfer.files;
if (!pos || options.readOnly) return;
if (files && files.length && window.FileReader && window.File) {
var n = files.length, text = Array(n), read = 0;
var loadFile = function(file, i) {
var reader = new FileReader;
reader.onload = function() {
text[i] = reader.result;
if (++read == n) {
pos = clipPos(pos);
operation(function() {
var end = replaceRange(text.join(""), pos, pos);
setSelectionUser(pos, end);
})();
}
};
reader.readAsText(file);
};
for (var i = 0; i < n; ++i) loadFile(files[i], i);
} else {
// Don't do a replace if the drop happened inside of the selected text.
if (draggingText && !(posLess(pos, sel.from) || posLess(sel.to, pos))) return;
try {
var text = e.dataTransfer.getData("Text");
if (text) {
compoundChange(function() {
var curFrom = sel.from, curTo = sel.to;
setSelectionUser(pos, pos);
if (draggingText) replaceRange("", curFrom, curTo);
replaceSelection(text);
focusInput();
});
}
}
catch(e){}
}
}
function onDragStart(e) {
var txt = getSelection();
e.dataTransfer.setData("Text", txt);
// Use dummy image instead of default browsers image.
if (e.dataTransfer.setDragImage)
e.dataTransfer.setDragImage(elt('img'), 0, 0);
}
function doHandleBinding(bound, dropShift) {
if (typeof bound == "string") {
bound = commands[bound];
if (!bound) return false;
}
var prevShift = shiftSelecting;
try {
if (options.readOnly) suppressEdits = true;
if (dropShift) shiftSelecting = null;
bound(instance);
} catch(e) {
if (e != Pass) throw e;
return false;
} finally {
shiftSelecting = prevShift;
suppressEdits = false;
}
return true;
}
var maybeTransition;
function handleKeyBinding(e) {
// Handle auto keymap transitions
var startMap = getKeyMap(options.keyMap), next = startMap.auto;
clearTimeout(maybeTransition);
if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() {
if (getKeyMap(options.keyMap) == startMap) {
options.keyMap = (next.call ? next.call(null, instance) : next);
}
}, 50);
var name = keyNames[e_prop(e, "keyCode")], handled = false;
var flipCtrlCmd = opera && mac;
if (name == null || e.altGraphKey) return false;
if (e_prop(e, "altKey")) name = "Alt-" + name;
if (e_prop(e, flipCtrlCmd ? "metaKey" : "ctrlKey")) name = "Ctrl-" + name;
if (e_prop(e, flipCtrlCmd ? "ctrlKey" : "metaKey")) name = "Cmd-" + name;
var stopped = false;
function stop() { stopped = true; }
if (e_prop(e, "shiftKey")) {
handled = lookupKey("Shift-" + name, options.extraKeys, options.keyMap,
function(b) {return doHandleBinding(b, true);}, stop)
|| lookupKey(name, options.extraKeys, options.keyMap, function(b) {
if (typeof b == "string" && /^go[A-Z]/.test(b)) return doHandleBinding(b);
}, stop);
} else {
handled = lookupKey(name, options.extraKeys, options.keyMap, doHandleBinding, stop);
}
if (stopped) handled = false;
if (handled) {
e_preventDefault(e);
restartBlink();
if (ie) { e.oldKeyCode = e.keyCode; e.keyCode = 0; }
}
return handled;
}
function handleCharBinding(e, ch) {
var handled = lookupKey("'" + ch + "'", options.extraKeys,
options.keyMap, function(b) { return doHandleBinding(b, true); });
if (handled) {
e_preventDefault(e);
restartBlink();
}
return handled;
}
var lastStoppedKey = null;
function onKeyDown(e) {
if (!focused) onFocus();
if (ie && e.keyCode == 27) { e.returnValue = false; }
if (pollingFast) { if (readInput()) pollingFast = false; }
if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
var code = e_prop(e, "keyCode");
// IE does strange things with escape.
setShift(code == 16 || e_prop(e, "shiftKey"));
// First give onKeyEvent option a chance to handle this.
var handled = handleKeyBinding(e);
if (opera) {
lastStoppedKey = handled ? code : null;
// Opera has no cut event... we try to at least catch the key combo
if (!handled && code == 88 && e_prop(e, mac ? "metaKey" : "ctrlKey"))
replaceSelection("");
}
}
function onKeyPress(e) {
if (pollingFast) readInput();
if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
var keyCode = e_prop(e, "keyCode"), charCode = e_prop(e, "charCode");
if (opera && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
if (((opera && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(e)) return;
var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
if (options.electricChars && mode.electricChars && options.smartIndent && !options.readOnly) {
if (mode.electricChars.indexOf(ch) > -1)
setTimeout(operation(function() {indentLine(sel.to.line, "smart");}), 75);
}
if (handleCharBinding(e, ch)) return;
fastPoll();
}
function onKeyUp(e) {
if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
if (e_prop(e, "keyCode") == 16) shiftSelecting = null;
}
function onFocus() {
if (options.readOnly == "nocursor") return;
if (!focused) {
if (options.onFocus) options.onFocus(instance);
focused = true;
if (scroller.className.search(/\bCodeMirror-focused\b/) == -1)
scroller.className += " CodeMirror-focused";
}
slowPoll();
restartBlink();
}
function onBlur() {
if (focused) {
if (options.onBlur) options.onBlur(instance);
focused = false;
if (bracketHighlighted)
operation(function(){
if (bracketHighlighted) { bracketHighlighted(); bracketHighlighted = null; }
})();
scroller.className = scroller.className.replace(" CodeMirror-focused", "");
}
clearInterval(blinker);
setTimeout(function() {if (!focused) shiftSelecting = null;}, 150);
}
// Replace the range from from to to by the strings in newText.
// Afterwards, set the selection to selFrom, selTo.
function updateLines(from, to, newText, selFrom, selTo) {
if (suppressEdits) return;
var old = [];
doc.iter(from.line, to.line + 1, function(line) {
old.push(newHL(line.text, line.markedSpans));
});
if (history) {
history.addChange(from.line, newText.length, old);
while (history.done.length > options.undoDepth) history.done.shift();
}
var lines = updateMarkedSpans(hlSpans(old[0]), hlSpans(lst(old)), from.ch, to.ch, newText);
updateLinesNoUndo(from, to, lines, selFrom, selTo);
}
function unredoHelper(from, to) {
if (!from.length) return;
var set = from.pop(), out = [];
for (var i = set.length - 1; i >= 0; i -= 1) {
var change = set[i];
var replaced = [], end = change.start + change.added;
doc.iter(change.start, end, function(line) { replaced.push(newHL(line.text, line.markedSpans)); });
out.push({start: change.start, added: change.old.length, old: replaced});
var pos = {line: change.start + change.old.length - 1,
ch: editEnd(hlText(lst(replaced)), hlText(lst(change.old)))};
updateLinesNoUndo({line: change.start, ch: 0}, {line: end - 1, ch: getLine(end-1).text.length},
change.old, pos, pos);
}
updateInput = true;
to.push(out);
}
function undo() {unredoHelper(history.done, history.undone);}
function redo() {unredoHelper(history.undone, history.done);}
function updateLinesNoUndo(from, to, lines, selFrom, selTo) {
if (suppressEdits) return;
var recomputeMaxLength = false, maxLineLength = maxLine.text.length;
if (!options.lineWrapping)
doc.iter(from.line, to.line + 1, function(line) {
if (!line.hidden && line.text.length == maxLineLength) {recomputeMaxLength = true; return true;}
});
if (from.line != to.line || lines.length > 1) gutterDirty = true;
var nlines = to.line - from.line, firstLine = getLine(from.line), lastLine = getLine(to.line);
var lastHL = lst(lines);
// First adjust the line structure
if (from.ch == 0 && to.ch == 0 && hlText(lastHL) == "") {
// This is a whole-line replace. Treated specially to make
// sure line objects move the way they are supposed to.
var added = [], prevLine = null;
for (var i = 0, e = lines.length - 1; i < e; ++i)
added.push(new Line(hlText(lines[i]), hlSpans(lines[i])));
lastLine.update(lastLine.text, hlSpans(lastHL));
if (nlines) doc.remove(from.line, nlines, callbacks);
if (added.length) doc.insert(from.line, added);
} else if (firstLine == lastLine) {
if (lines.length == 1) {
firstLine.update(firstLine.text.slice(0, from.ch) + hlText(lines[0]) + firstLine.text.slice(to.ch), hlSpans(lines[0]));
} else {
for (var added = [], i = 1, e = lines.length - 1; i < e; ++i)
added.push(new Line(hlText(lines[i]), hlSpans(lines[i])));
added.push(new Line(hlText(lastHL) + firstLine.text.slice(to.ch), hlSpans(lastHL)));
firstLine.update(firstLine.text.slice(0, from.ch) + hlText(lines[0]), hlSpans(lines[0]));
doc.insert(from.line + 1, added);
}
} else if (lines.length == 1) {
firstLine.update(firstLine.text.slice(0, from.ch) + hlText(lines[0]) + lastLine.text.slice(to.ch), hlSpans(lines[0]));
doc.remove(from.line + 1, nlines, callbacks);
} else {
var added = [];
firstLine.update(firstLine.text.slice(0, from.ch) + hlText(lines[0]), hlSpans(lines[0]));
lastLine.update(hlText(lastHL) + lastLine.text.slice(to.ch), hlSpans(lastHL));
for (var i = 1, e = lines.length - 1; i < e; ++i)
added.push(new Line(hlText(lines[i]), hlSpans(lines[i])));
if (nlines > 1) doc.remove(from.line + 1, nlines - 1, callbacks);
doc.insert(from.line + 1, added);
}
if (options.lineWrapping) {
var perLine = Math.max(5, scroller.clientWidth / charWidth() - 3);
doc.iter(from.line, from.line + lines.length, function(line) {
if (line.hidden) return;
var guess = Math.ceil(line.text.length / perLine) || 1;
if (guess != line.height) updateLineHeight(line, guess);
});
} else {
doc.iter(from.line, from.line + lines.length, function(line) {
var l = line.text;
if (!line.hidden && l.length > maxLineLength) {
maxLine = line; maxLineLength = l.length; maxLineChanged = true;
recomputeMaxLength = false;
}
});
if (recomputeMaxLength) updateMaxLine = true;
}
// Adjust frontier, schedule worker
frontier = Math.min(frontier, from.line);
startWorker(400);
var lendiff = lines.length - nlines - 1;
// Remember that these lines changed, for updating the display
changes.push({from: from.line, to: to.line + 1, diff: lendiff});
if (options.onChange) {
// Normalize lines to contain only strings, since that's what
// the change event handler expects
for (var i = 0; i < lines.length; ++i)
if (typeof lines[i] != "string") lines[i] = lines[i].text;
var changeObj = {from: from, to: to, text: lines};
if (textChanged) {
for (var cur = textChanged; cur.next; cur = cur.next) {}
cur.next = changeObj;
} else textChanged = changeObj;
}
// Update the selection
function updateLine(n) {return n <= Math.min(to.line, to.line + lendiff) ? n : n + lendiff;}
setSelection(clipPos(selFrom), clipPos(selTo),
updateLine(sel.from.line), updateLine(sel.to.line));
}
function needsScrollbar() {
var realHeight = doc.height * textHeight() + 2 * paddingTop();
return realHeight * .99 > scroller.offsetHeight ? realHeight : false;
}
function updateVerticalScroll(scrollTop) {
var scrollHeight = needsScrollbar();
scrollbar.style.display = scrollHeight ? "block" : "none";
if (scrollHeight) {
scrollbarInner.style.height = sizer.style.minHeight = scrollHeight + "px";
scrollbar.style.height = scroller.clientHeight + "px";
if (scrollTop != null) {
scrollbar.scrollTop = scroller.scrollTop = scrollTop;
// 'Nudge' the scrollbar to work around a Webkit bug where,
// in some situations, we'd end up with a scrollbar that
// reported its scrollTop (and looked) as expected, but
// *behaved* as if it was still in a previous state (i.e.
// couldn't scroll up, even though it appeared to be at the
// bottom).
if (webkit) setTimeout(function() {
if (scrollbar.scrollTop != scrollTop) return;
scrollbar.scrollTop = scrollTop + (scrollTop ? -1 : 1);
scrollbar.scrollTop = scrollTop;
}, 0);
}
} else {
sizer.style.minHeight = "";
}
// Position the mover div to align with the current virtual scroll position
mover.style.top = displayOffset * textHeight() + "px";
}
function computeMaxLength() {
maxLine = getLine(0); maxLineChanged = true;
var maxLineLength = maxLine.text.length;
doc.iter(1, doc.size, function(line) {
var l = line.text;
if (!line.hidden && l.length > maxLineLength) {
maxLineLength = l.length; maxLine = line;
}
});
updateMaxLine = false;
}
function replaceRange(code, from, to) {
from = clipPos(from);
if (!to) to = from; else to = clipPos(to);
code = splitLines(code);
function adjustPos(pos) {
if (posLess(pos, from)) return pos;
if (!posLess(to, pos)) return end;
var line = pos.line + code.length - (to.line - from.line) - 1;
var ch = pos.ch;
if (pos.line == to.line)
ch += lst(code).length - (to.ch - (to.line == from.line ? from.ch : 0));
return {line: line, ch: ch};
}
var end;
replaceRange1(code, from, to, function(end1) {
end = end1;
return {from: adjustPos(sel.from), to: adjustPos(sel.to)};
});
return end;
}
function replaceSelection(code, collapse) {
replaceRange1(splitLines(code), sel.from, sel.to, function(end) {
if (collapse == "end") return {from: end, to: end};
else if (collapse == "start") return {from: sel.from, to: sel.from};
else return {from: sel.from, to: end};
});
}
function replaceRange1(code, from, to, computeSel) {
var endch = code.length == 1 ? code[0].length + from.ch : lst(code).length;
var newSel = computeSel({line: from.line + code.length - 1, ch: endch});
updateLines(from, to, code, newSel.from, newSel.to);
}
function getRange(from, to, lineSep) {
var l1 = from.line, l2 = to.line;
if (l1 == l2) return getLine(l1).text.slice(from.ch, to.ch);
var code = [getLine(l1).text.slice(from.ch)];
doc.iter(l1 + 1, l2, function(line) { code.push(line.text); });
code.push(getLine(l2).text.slice(0, to.ch));
return code.join(lineSep || "\n");
}
function getSelection(lineSep) {
return getRange(sel.from, sel.to, lineSep);
}
function slowPoll() {
if (pollingFast) return;
poll.set(options.pollInterval, function() {
readInput();
if (focused) slowPoll();
});
}
function fastPoll() {
var missed = false;
pollingFast = true;
function p() {
var changed = readInput();
if (!changed && !missed) {missed = true; poll.set(60, p);}
else {pollingFast = false; slowPoll();}
}
poll.set(20, p);
}
// Previnput is a hack to work with IME. If we reset the textarea
// on every change, that breaks IME. So we look for changes
// compared to the previous content instead. (Modern browsers have
// events that indicate IME taking place, but these are not widely
// supported or compatible enough yet to rely on.)
var prevInput = "";
function readInput() {
if (!focused || hasSelection(input) || options.readOnly) return false;
var text = input.value;
if (text == prevInput) return false;
if (!nestedOperation) startOperation();
shiftSelecting = null;
var same = 0, l = Math.min(prevInput.length, text.length);
while (same < l && prevInput[same] == text[same]) ++same;
if (same < prevInput.length)
sel.from = {line: sel.from.line, ch: sel.from.ch - (prevInput.length - same)};
else if (overwrite && posEq(sel.from, sel.to) && !pasteIncoming)
sel.to = {line: sel.to.line, ch: Math.min(getLine(sel.to.line).text.length, sel.to.ch + (text.length - same))};
replaceSelection(text.slice(same), "end");
if (text.length > 1000) { input.value = prevInput = ""; }
else prevInput = text;
if (!nestedOperation) endOperation();
pasteIncoming = false;
return true;
}
function resetInput(user) {
if (!posEq(sel.from, sel.to)) {
prevInput = "";
input.value = getSelection();
if (focused) selectInput(input);
} else if (user) prevInput = input.value = "";
}
function focusInput() {
if (options.readOnly != "nocursor") input.focus();
}
function scrollCursorIntoView() {
var coords = calculateCursorCoords();
scrollIntoView(coords.x, coords.y, coords.x, coords.yBot);
if (!focused) return;
var box = sizer.getBoundingClientRect(), doScroll = null;
if (coords.y + box.top < 0) doScroll = true;
else if (coords.y + box.top + textHeight() > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
if (doScroll != null) {
var hidden = cursor.style.display == "none";
if (hidden) {
cursor.style.display = "";
cursor.style.left = coords.x + "px";
cursor.style.top = (coords.y - displayOffset) + "px";
}
cursor.scrollIntoView(doScroll);
if (hidden) cursor.style.display = "none";
}
}
function calculateCursorCoords() {
var cursor = localCoords(sel.inverted ? sel.from : sel.to);
var x = options.lineWrapping ? Math.min(cursor.x, lineSpace.offsetWidth) : cursor.x;
return {x: x, y: cursor.y, yBot: cursor.yBot};
}
function scrollIntoView(x1, y1, x2, y2) {
var scrollPos = calculateScrollPos(x1, y1, x2, y2);
if (scrollPos.scrollLeft != null) {scroller.scrollLeft = scrollPos.scrollLeft;}
if (scrollPos.scrollTop != null) {scrollbar.scrollTop = scroller.scrollTop = scrollPos.scrollTop;}
}
function calculateScrollPos(x1, y1, x2, y2) {
var pl = paddingLeft(), pt = paddingTop();
y1 += pt; y2 += pt; x1 += pl; x2 += pl;
var screen = scroller.clientHeight, screentop = scrollbar.scrollTop, result = {};
var docBottom = needsScrollbar() || Infinity;
var atTop = y1 < pt + 10, atBottom = y2 + pt > docBottom - 10;
if (y1 < screentop) result.scrollTop = atTop ? 0 : Math.max(0, y1);
else if (y2 > screentop + screen) result.scrollTop = (atBottom ? docBottom : y2) - screen;
var screenw = scroller.clientWidth, screenleft = scroller.scrollLeft;
var gutterw = options.fixedGutter ? gutter.clientWidth : 0;
var atLeft = x1 < gutterw + pl + 10;
if (x1 < screenleft + gutterw || atLeft) {
if (atLeft) x1 = 0;
result.scrollLeft = Math.max(0, x1 - 10 - gutterw);
} else if (x2 > screenw + screenleft - 3) {
result.scrollLeft = x2 + 10 - screenw;
}
return result;
}
function visibleLines(scrollTop) {
var lh = textHeight(), top = (scrollTop != null ? scrollTop : scrollbar.scrollTop) - paddingTop();
var fromHeight = Math.max(0, Math.floor(top / lh));
var toHeight = Math.ceil((top + scroller.clientHeight) / lh);
return {from: lineAtHeight(doc, fromHeight),
to: lineAtHeight(doc, toHeight)};
}
// Uses a set of changes plus the current scroll position to
// determine which DOM updates have to be made, and makes the
// updates.
function updateDisplay(changes, suppressCallback, scrollTop) {
if (!scroller.clientWidth) {
showingFrom = showingTo = displayOffset = 0;
return;
}
// Compute the new visible window
// If scrollTop is specified, use that to determine which lines
// to render instead of the current scrollbar position.
var visible = visibleLines(scrollTop);
// Bail out if the visible area is already rendered and nothing changed.
if (changes !== true && changes.length == 0 && visible.from > showingFrom && visible.to < showingTo) {
updateVerticalScroll(scrollTop);
return;
}
var from = Math.max(visible.from - 100, 0), to = Math.min(doc.size, visible.to + 100);
if (showingFrom < from && from - showingFrom < 20) from = showingFrom;
if (showingTo > to && showingTo - to < 20) to = Math.min(doc.size, showingTo);
// Create a range of theoretically intact lines, and punch holes
// in that using the change info.
var intact = changes === true ? [] :
computeIntact([{from: showingFrom, to: showingTo, domStart: 0}], changes);
// Clip off the parts that won't be visible
var intactLines = 0;
for (var i = 0; i < intact.length; ++i) {
var range = intact[i];
if (range.from < from) {range.domStart += (from - range.from); range.from = from;}
if (range.to > to) range.to = to;
if (range.from >= range.to) intact.splice(i--, 1);
else intactLines += range.to - range.from;
}
if (intactLines == to - from && from == showingFrom && to == showingTo) {
updateVerticalScroll(scrollTop);
return;
}
intact.sort(function(a, b) {return a.domStart - b.domStart;});
var th = textHeight(), gutterDisplay = gutter.style.display;
lineDiv.style.display = "none";
patchDisplay(from, to, intact);
lineDiv.style.display = gutter.style.display = "";
var different = from != showingFrom || to != showingTo || lastSizeC != scroller.clientHeight + th;
// This is just a bogus formula that detects when the editor is
// resized or the font size changes.
if (different) lastSizeC = scroller.clientHeight + th;
if (from != showingFrom || to != showingTo && options.onViewportChange)
setTimeout(function(){
if (options.onViewportChange) options.onViewportChange(instance, from, to);
});
showingFrom = from; showingTo = to;
displayOffset = heightAtLine(doc, from);
startWorker(100);
// Since this is all rather error prone, it is honoured with the
// only assertion in the whole file.
if (lineDiv.childNodes.length != showingTo - showingFrom)
throw new Error("BAD PATCH! " + JSON.stringify(intact) + " size=" + (showingTo - showingFrom) +
" nodes=" + lineDiv.childNodes.length);
function checkHeights() {
var curNode = lineDiv.firstChild, heightChanged = false;
doc.iter(showingFrom, showingTo, function(line) {
// Work around bizarro IE7 bug where, sometimes, our curNode
// is magically replaced with a new node in the DOM, leaving
// us with a reference to an orphan (nextSibling-less) node.
if (!curNode) return;
if (!line.hidden) {
var height = Math.round(curNode.offsetHeight / th) || 1;
if (line.height != height) {
updateLineHeight(line, height);
gutterDirty = heightChanged = true;
}
}
curNode = curNode.nextSibling;
});
return heightChanged;
}
if (options.lineWrapping) checkHeights();
gutter.style.display = gutterDisplay;
if (different || gutterDirty) {
// If the gutter grew in size, re-check heights. If those changed, re-draw gutter.
updateGutter() && options.lineWrapping && checkHeights() && updateGutter();
}
updateVerticalScroll(scrollTop);
updateSelection();
if (!suppressCallback && options.onUpdate) options.onUpdate(instance);
return true;
}
function computeIntact(intact, changes) {
for (var i = 0, l = changes.length || 0; i < l; ++i) {
var change = changes[i], intact2 = [], diff = change.diff || 0;
for (var j = 0, l2 = intact.length; j < l2; ++j) {
var range = intact[j];
if (change.to <= range.from && change.diff)
intact2.push({from: range.from + diff, to: range.to + diff,
domStart: range.domStart});
else if (change.to <= range.from || change.from >= range.to)
intact2.push(range);
else {
if (change.from > range.from)
intact2.push({from: range.from, to: change.from, domStart: range.domStart});
if (change.to < range.to)
intact2.push({from: change.to + diff, to: range.to + diff,
domStart: range.domStart + (change.to - range.from)});
}
}
intact = intact2;
}
return intact;
}
function patchDisplay(from, to, intact) {
function killNode(node) {
var tmp = node.nextSibling;
node.parentNode.removeChild(node);
return tmp;
}
// The first pass removes the DOM nodes that aren't intact.
if (!intact.length) removeChildren(lineDiv);
else {
var domPos = 0, curNode = lineDiv.firstChild, n;
for (var i = 0; i < intact.length; ++i) {
var cur = intact[i];
while (cur.domStart > domPos) {curNode = killNode(curNode); domPos++;}
for (var j = 0, e = cur.to - cur.from; j < e; ++j) {curNode = curNode.nextSibling; domPos++;}
}
while (curNode) curNode = killNode(curNode);
}
// This pass fills in the lines that actually changed.
var nextIntact = intact.shift(), curNode = lineDiv.firstChild, j = from;
doc.iter(from, to, function(line) {
if (nextIntact && nextIntact.to == j) nextIntact = intact.shift();
if (!nextIntact || nextIntact.from > j) {
if (line.hidden) var lineElement = elt("pre");
else {
var lineElement = lineContent(line);
if (line.className) lineElement.className = line.className;
// Kludge to make sure the styled element lies behind the selection (by z-index)
if (line.bgClassName) {
var pre = elt("pre", "\u00a0", line.bgClassName, "position: absolute; left: 0; right: 0; top: 0; bottom: 0; z-index: -2");
lineElement = elt("div", [pre, lineElement], null, "position: relative");
}
}
lineDiv.insertBefore(lineElement, curNode);
} else {
curNode = curNode.nextSibling;
}
++j;
});
}
function updateGutter() {
if (!options.gutter && !options.lineNumbers) return;
var hText = mover.offsetHeight, hEditor = scroller.clientHeight;
gutter.style.height = (hText - hEditor < 2 ? hEditor : hText) + "px";
var fragment = document.createDocumentFragment(), i = showingFrom, normalNode;
doc.iter(showingFrom, Math.max(showingTo, showingFrom + 1), function(line) {
if (line.hidden) {
fragment.appendChild(elt("pre"));
} else {
var marker = line.gutterMarker;
var text = options.lineNumbers ? options.lineNumberFormatter(i + options.firstLineNumber) : null;
if (marker && marker.text)
text = marker.text.replace("%N%", text != null ? text : "");
else if (text == null)
text = "\u00a0";
var markerElement = fragment.appendChild(elt("pre", null, marker && marker.style));
markerElement.innerHTML = text;
for (var j = 1; j < line.height; ++j) {
markerElement.appendChild(elt("br"));
markerElement.appendChild(document.createTextNode("\u00a0"));
}
if (!marker) normalNode = i;
}
++i;
});
gutter.style.display = "none";
removeChildrenAndAdd(gutterText, fragment);
// Make sure scrolling doesn't cause number gutter size to pop
if (normalNode != null && options.lineNumbers) {
var node = gutterText.childNodes[normalNode - showingFrom];
var minwidth = String(doc.size).length, val = eltText(node.firstChild), pad = "";
while (val.length + pad.length < minwidth) pad += "\u00a0";
if (pad) node.insertBefore(document.createTextNode(pad), node.firstChild);
}
gutter.style.display = "";
var resized = Math.abs((parseInt(lineSpace.style.marginLeft) || 0) - gutter.offsetWidth) > 2;
lineSpace.style.marginLeft = gutter.offsetWidth + "px";
gutterDirty = false;
return resized;
}
function updateSelection() {
var collapsed = posEq(sel.from, sel.to);
var fromPos = localCoords(sel.from, true);
var toPos = collapsed ? fromPos : localCoords(sel.to, true);
var headPos = sel.inverted ? fromPos : toPos, th = textHeight();
var wrapOff = eltOffset(wrapper), lineOff = eltOffset(lineDiv);
inputDiv.style.top = Math.max(0, Math.min(scroller.offsetHeight, headPos.y + lineOff.top - wrapOff.top)) + "px";
inputDiv.style.left = Math.max(0, Math.min(scroller.offsetWidth, headPos.x + lineOff.left - wrapOff.left)) + "px";
if (collapsed) {
cursor.style.top = headPos.y + "px";
cursor.style.left = (options.lineWrapping ? Math.min(headPos.x, lineSpace.offsetWidth) : headPos.x) + "px";
cursor.style.display = "";
selectionDiv.style.display = "none";
} else {
var sameLine = fromPos.y == toPos.y, fragment = document.createDocumentFragment();
var clientWidth = lineSpace.clientWidth || lineSpace.offsetWidth;
var clientHeight = lineSpace.clientHeight || lineSpace.offsetHeight;
var add = function(left, top, right, height) {
var rstyle = quirksMode ? "width: " + (!right ? clientWidth : clientWidth - right - left) + "px"
: "right: " + right + "px";
fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
"px; top: " + top + "px; " + rstyle + "; height: " + height + "px"));
};
if (sel.from.ch && fromPos.y >= 0) {
var right = sameLine ? clientWidth - toPos.x : 0;
add(fromPos.x, fromPos.y, right, th);
}
var middleStart = Math.max(0, fromPos.y + (sel.from.ch ? th : 0));
var middleHeight = Math.min(toPos.y, clientHeight) - middleStart;
if (middleHeight > 0.2 * th)
add(0, middleStart, 0, middleHeight);
if ((!sameLine || !sel.from.ch) && toPos.y < clientHeight - .5 * th)
add(0, toPos.y, clientWidth - toPos.x, th);
removeChildrenAndAdd(selectionDiv, fragment);
cursor.style.display = "none";
selectionDiv.style.display = "";
}
}
function setShift(val) {
if (val) shiftSelecting = shiftSelecting || (sel.inverted ? sel.to : sel.from);
else shiftSelecting = null;
}
function setSelectionUser(from, to) {
var sh = shiftSelecting && clipPos(shiftSelecting);
if (sh) {
if (posLess(sh, from)) from = sh;
else if (posLess(to, sh)) to = sh;
}
setSelection(from, to);
userSelChange = true;
}
// Update the selection. Last two args are only used by
// updateLines, since they have to be expressed in the line
// numbers before the update.
function setSelection(from, to, oldFrom, oldTo) {
goalColumn = null;
if (oldFrom == null) {oldFrom = sel.from.line; oldTo = sel.to.line;}
if (posEq(sel.from, from) && posEq(sel.to, to)) return;
if (posLess(to, from)) {var tmp = to; to = from; from = tmp;}
// Skip over hidden lines.
if (from.line != oldFrom) {
var from1 = skipHidden(from, oldFrom, sel.from.ch);
// If there is no non-hidden line left, force visibility on current line
if (!from1) setLineHidden(from.line, false);
else from = from1;
}
if (to.line != oldTo) to = skipHidden(to, oldTo, sel.to.ch);
if (posEq(from, to)) sel.inverted = false;
else if (posEq(from, sel.to)) sel.inverted = false;
else if (posEq(to, sel.from)) sel.inverted = true;
if (options.autoClearEmptyLines && posEq(sel.from, sel.to)) {
var head = sel.inverted ? from : to;
if (head.line != sel.from.line && sel.from.line < doc.size) {
var oldLine = getLine(sel.from.line);
if (/^\s+$/.test(oldLine.text))
setTimeout(operation(function() {
if (oldLine.parent && /^\s+$/.test(oldLine.text)) {
var no = lineNo(oldLine);
replaceRange("", {line: no, ch: 0}, {line: no, ch: oldLine.text.length});
}
}, 10));
}
}
sel.from = from; sel.to = to;
selectionChanged = true;
}
function skipHidden(pos, oldLine, oldCh) {
function getNonHidden(dir) {
var lNo = pos.line + dir, end = dir == 1 ? doc.size : -1;
while (lNo != end) {
var line = getLine(lNo);
if (!line.hidden) {
var ch = pos.ch;
if (toEnd || ch > oldCh || ch > line.text.length) ch = line.text.length;
return {line: lNo, ch: ch};
}
lNo += dir;
}
}
var line = getLine(pos.line);
var toEnd = pos.ch == line.text.length && pos.ch != oldCh;
if (!line.hidden) return pos;
if (pos.line >= oldLine) return getNonHidden(1) || getNonHidden(-1);
else return getNonHidden(-1) || getNonHidden(1);
}
function setCursor(line, ch, user) {
var pos = clipPos({line: line, ch: ch || 0});
(user ? setSelectionUser : setSelection)(pos, pos);
}
function clipLine(n) {return Math.max(0, Math.min(n, doc.size-1));}
function clipPos(pos) {
if (pos.line < 0) return {line: 0, ch: 0};
if (pos.line >= doc.size) return {line: doc.size-1, ch: getLine(doc.size-1).text.length};
var ch = pos.ch, linelen = getLine(pos.line).text.length;
if (ch == null || ch > linelen) return {line: pos.line, ch: linelen};
else if (ch < 0) return {line: pos.line, ch: 0};
else return pos;
}
function findPosH(dir, unit) {
var end = sel.inverted ? sel.from : sel.to, line = end.line, ch = end.ch;
var lineObj = getLine(line);
function findNextLine() {
for (var l = line + dir, e = dir < 0 ? -1 : doc.size; l != e; l += dir) {
var lo = getLine(l);
if (!lo.hidden) { line = l; lineObj = lo; return true; }
}
}
function moveOnce(boundToLine) {
if (ch == (dir < 0 ? 0 : lineObj.text.length)) {
if (!boundToLine && findNextLine()) ch = dir < 0 ? lineObj.text.length : 0;
else return false;
} else ch += dir;
return true;
}
if (unit == "char") moveOnce();
else if (unit == "column") moveOnce(true);
else if (unit == "word") {
var sawWord = false;
for (;;) {
if (dir < 0) if (!moveOnce()) break;
if (isWordChar(lineObj.text.charAt(ch))) sawWord = true;
else if (sawWord) {if (dir < 0) {dir = 1; moveOnce();} break;}
if (dir > 0) if (!moveOnce()) break;
}
}
return {line: line, ch: ch};
}
function moveH(dir, unit) {
var pos = dir < 0 ? sel.from : sel.to;
if (shiftSelecting || posEq(sel.from, sel.to)) pos = findPosH(dir, unit);
setCursor(pos.line, pos.ch, true);
}
function deleteH(dir, unit) {
if (!posEq(sel.from, sel.to)) replaceRange("", sel.from, sel.to);
else if (dir < 0) replaceRange("", findPosH(dir, unit), sel.to);
else replaceRange("", sel.from, findPosH(dir, unit));
userSelChange = true;
}
function moveV(dir, unit) {
var dist = 0, pos = localCoords(sel.inverted ? sel.from : sel.to, true);
if (goalColumn != null) pos.x = goalColumn;
if (unit == "page") {
var screen = Math.min(scroller.clientHeight, window.innerHeight || document.documentElement.clientHeight);
var target = coordsChar(pos.x, pos.y + screen * dir);
} else if (unit == "line") {
var th = textHeight();
var target = coordsChar(pos.x, pos.y + .5 * th + dir * th);
}
if (unit == "page") scrollbar.scrollTop += localCoords(target, true).y - pos.y;
setCursor(target.line, target.ch, true);
goalColumn = pos.x;
}
function findWordAt(pos) {
var line = getLine(pos.line).text;
var start = pos.ch, end = pos.ch;
if (line) {
if (pos.after === false || end == line.length) --start; else ++end;
var startChar = line.charAt(start);
var check = isWordChar(startChar) ? isWordChar :
/\s/.test(startChar) ? function(ch) {return /\s/.test(ch);} :
function(ch) {return !/\s/.test(ch) && isWordChar(ch);};
while (start > 0 && check(line.charAt(start - 1))) --start;
while (end < line.length && check(line.charAt(end))) ++end;
}
return {from: {line: pos.line, ch: start}, to: {line: pos.line, ch: end}};
}
function selectLine(line) {
setSelectionUser({line: line, ch: 0}, clipPos({line: line + 1, ch: 0}));
}
function indentSelected(mode) {
if (posEq(sel.from, sel.to)) return indentLine(sel.from.line, mode);
var e = sel.to.line - (sel.to.ch ? 0 : 1);
for (var i = sel.from.line; i <= e; ++i) indentLine(i, mode);
}
function indentLine(n, how) {
if (!how) how = "add";
if (how == "smart") {
if (!mode.indent) how = "prev";
else var state = getStateBefore(n);
}
var line = getLine(n), curSpace = line.indentation(options.tabSize),
curSpaceString = line.text.match(/^\s*/)[0], indentation;
if (how == "smart") {
indentation = mode.indent(state, line.text.slice(curSpaceString.length), line.text);
if (indentation == Pass) how = "prev";
}
if (how == "prev") {
if (n) indentation = getLine(n-1).indentation(options.tabSize);
else indentation = 0;
}
else if (how == "add") indentation = curSpace + options.indentUnit;
else if (how == "subtract") indentation = curSpace - options.indentUnit;
indentation = Math.max(0, indentation);
var diff = indentation - curSpace;
var indentString = "", pos = 0;
if (options.indentWithTabs)
for (var i = Math.floor(indentation / options.tabSize); i; --i) {pos += options.tabSize; indentString += "\t";}
if (pos < indentation) indentString += spaceStr(indentation - pos);
if (indentString != curSpaceString)
replaceRange(indentString, {line: n, ch: 0}, {line: n, ch: curSpaceString.length});
line.stateAfter = null;
}
function loadMode() {
mode = CodeMirror.getMode(options, options.mode);
doc.iter(0, doc.size, function(line) { line.stateAfter = null; });
frontier = 0;
startWorker(100);
}
function gutterChanged() {
var visible = options.gutter || options.lineNumbers;
gutter.style.display = visible ? "" : "none";
if (visible) gutterDirty = true;
else lineDiv.parentNode.style.marginLeft = 0;
}
function wrappingChanged(from, to) {
if (options.lineWrapping) {
wrapper.className += " CodeMirror-wrap";
var perLine = scroller.clientWidth / charWidth() - 3;
doc.iter(0, doc.size, function(line) {
if (line.hidden) return;
var guess = Math.ceil(line.text.length / perLine) || 1;
if (guess != 1) updateLineHeight(line, guess);
});
lineSpace.style.minWidth = widthForcer.style.left = "";
} else {
wrapper.className = wrapper.className.replace(" CodeMirror-wrap", "");
computeMaxLength();
doc.iter(0, doc.size, function(line) {
if (line.height != 1 && !line.hidden) updateLineHeight(line, 1);
});
}
changes.push({from: 0, to: doc.size});
}
function themeChanged() {
scroller.className = scroller.className.replace(/\s*cm-s-\S+/g, "") +
options.theme.replace(/(^|\s)\s*/g, " cm-s-");
}
function keyMapChanged() {
var style = keyMap[options.keyMap].style;
wrapper.className = wrapper.className.replace(/\s*cm-keymap-\S+/g, "") +
(style ? " cm-keymap-" + style : "");
}
function TextMarker(type, style) { this.lines = []; this.type = type; if (style) this.style = style; }
TextMarker.prototype.clear = operation(function() {
var min, max;
for (var i = 0; i < this.lines.length; ++i) {
var line = this.lines[i];
var span = getMarkedSpanFor(line.markedSpans, this);
if (span.from != null) min = lineNo(line);
if (span.to != null) max = lineNo(line);
line.markedSpans = removeMarkedSpan(line.markedSpans, span);
}
if (min != null) changes.push({from: min, to: max + 1});
this.lines.length = 0;
this.explicitlyCleared = true;
});
TextMarker.prototype.find = function() {
var from, to;
for (var i = 0; i < this.lines.length; ++i) {
var line = this.lines[i];
var span = getMarkedSpanFor(line.markedSpans, this);
if (span.from != null || span.to != null) {
var found = lineNo(line);
if (span.from != null) from = {line: found, ch: span.from};
if (span.to != null) to = {line: found, ch: span.to};
}
}
if (this.type == "bookmark") return from;
return from && {from: from, to: to};
};
function markText(from, to, className, options) {
from = clipPos(from); to = clipPos(to);
var marker = new TextMarker("range", className);
if (options) for (var opt in options) if (options.hasOwnProperty(opt))
marker[opt] = options[opt];
var curLine = from.line;
doc.iter(curLine, to.line + 1, function(line) {
var span = {from: curLine == from.line ? from.ch : null,
to: curLine == to.line ? to.ch : null,
marker: marker};
line.markedSpans = (line.markedSpans || []).concat([span]);
marker.lines.push(line);
++curLine;
});
changes.push({from: from.line, to: to.line + 1});
return marker;
}
function setBookmark(pos) {
pos = clipPos(pos);
var marker = new TextMarker("bookmark"), line = getLine(pos.line);
history.addChange(pos.line, 1, [newHL(line.text, line.markedSpans)], true);
var span = {from: pos.ch, to: pos.ch, marker: marker};
line.markedSpans = (line.markedSpans || []).concat([span]);
marker.lines.push(line);
return marker;
}
function findMarksAt(pos) {
pos = clipPos(pos);
var markers = [], spans = getLine(pos.line).markedSpans;
if (spans) for (var i = 0; i < spans.length; ++i) {
var span = spans[i];
if ((span.from == null || span.from <= pos.ch) &&
(span.to == null || span.to >= pos.ch))
markers.push(span.marker);
}
return markers;
}
function addGutterMarker(line, text, className) {
if (typeof line == "number") line = getLine(clipLine(line));
line.gutterMarker = {text: text, style: className};
gutterDirty = true;
return line;
}
function removeGutterMarker(line) {
if (typeof line == "number") line = getLine(clipLine(line));
line.gutterMarker = null;
gutterDirty = true;
}
function changeLine(handle, op) {
var no = handle, line = handle;
if (typeof handle == "number") line = getLine(clipLine(handle));
else no = lineNo(handle);
if (no == null) return null;
if (op(line, no)) changes.push({from: no, to: no + 1});
else return null;
return line;
}
function setLineClass(handle, className, bgClassName) {
return changeLine(handle, function(line) {
if (line.className != className || line.bgClassName != bgClassName) {
line.className = className;
line.bgClassName = bgClassName;
return true;
}
});
}
function setLineHidden(handle, hidden) {
return changeLine(handle, function(line, no) {
if (line.hidden != hidden) {
line.hidden = hidden;
if (!options.lineWrapping) {
if (hidden && line.text.length == maxLine.text.length) {
updateMaxLine = true;
} else if (!hidden && line.text.length > maxLine.text.length) {
maxLine = line; updateMaxLine = false;
}
}
updateLineHeight(line, hidden ? 0 : 1);
var fline = sel.from.line, tline = sel.to.line;
if (hidden && (fline == no || tline == no)) {
var from = fline == no ? skipHidden({line: fline, ch: 0}, fline, 0) : sel.from;
var to = tline == no ? skipHidden({line: tline, ch: 0}, tline, 0) : sel.to;
// Can't hide the last visible line, we'd have no place to put the cursor
if (!to) return;
setSelection(from, to);
}
return (gutterDirty = true);
}
});
}
function lineInfo(line) {
if (typeof line == "number") {
if (!isLine(line)) return null;
var n = line;
line = getLine(line);
if (!line) return null;
} else {
var n = lineNo(line);
if (n == null) return null;
}
var marker = line.gutterMarker;
return {line: n, handle: line, text: line.text, markerText: marker && marker.text,
markerClass: marker && marker.style, lineClass: line.className, bgClass: line.bgClassName};
}
function measureLine(line, ch) {
if (ch == 0) return {top: 0, left: 0};
var pre = lineContent(line, ch);
removeChildrenAndAdd(measure, pre);
var anchor = pre.anchor;
var top = anchor.offsetTop, left = anchor.offsetLeft;
// Older IEs report zero offsets for spans directly after a wrap
if (ie && top == 0 && left == 0) {
var backup = elt("span", "x");
anchor.parentNode.insertBefore(backup, anchor.nextSibling);
top = backup.offsetTop;
}
return {top: top, left: left};
}
function localCoords(pos, inLineWrap) {
var x, lh = textHeight(), y = lh * (heightAtLine(doc, pos.line) - (inLineWrap ? displayOffset : 0));
if (pos.ch == 0) x = 0;
else {
var sp = measureLine(getLine(pos.line), pos.ch);
x = sp.left;
if (options.lineWrapping) y += Math.max(0, sp.top);
}
return {x: x, y: y, yBot: y + lh};
}
// Coords must be lineSpace-local
function coordsChar(x, y) {
var th = textHeight(), cw = charWidth(), heightPos = displayOffset + Math.floor(y / th);
if (heightPos < 0) return {line: 0, ch: 0};
var lineNo = lineAtHeight(doc, heightPos);
if (lineNo >= doc.size) return {line: doc.size - 1, ch: getLine(doc.size - 1).text.length};
var lineObj = getLine(lineNo), text = lineObj.text;
var tw = options.lineWrapping, innerOff = tw ? heightPos - heightAtLine(doc, lineNo) : 0;
if (x <= 0 && innerOff == 0) return {line: lineNo, ch: 0};
var wrongLine = false;
function getX(len) {
var sp = measureLine(lineObj, len);
if (tw) {
var off = Math.round(sp.top / th);
wrongLine = off != innerOff;
return Math.max(0, sp.left + (off - innerOff) * scroller.clientWidth);
}
return sp.left;
}
var from = 0, fromX = 0, to = text.length, toX;
// Guess a suitable upper bound for our search.
var estimated = Math.min(to, Math.ceil((x + innerOff * scroller.clientWidth * .9) / cw));
for (;;) {
var estX = getX(estimated);
if (estX <= x && estimated < to) estimated = Math.min(to, Math.ceil(estimated * 1.2));
else {toX = estX; to = estimated; break;}
}
if (x > toX) return {line: lineNo, ch: to};
// Try to guess a suitable lower bound as well.
estimated = Math.floor(to * 0.8); estX = getX(estimated);
if (estX < x) {from = estimated; fromX = estX;}
// Do a binary search between these bounds.
for (;;) {
if (to - from <= 1) {
var after = x - fromX < toX - x;
return {line: lineNo, ch: after ? from : to, after: after};
}
var middle = Math.ceil((from + to) / 2), middleX = getX(middle);
if (middleX > x) {to = middle; toX = middleX; if (wrongLine) toX += 1000; }
else {from = middle; fromX = middleX;}
}
}
function pageCoords(pos) {
var local = localCoords(pos, true), off = eltOffset(lineSpace);
return {x: off.left + local.x, y: off.top + local.y, yBot: off.top + local.yBot};
}
var cachedHeight, cachedHeightFor, measurePre;
function textHeight() {
if (measurePre == null) {
measurePre = elt("pre");
for (var i = 0; i < 49; ++i) {
measurePre.appendChild(document.createTextNode("x"));
measurePre.appendChild(elt("br"));
}
measurePre.appendChild(document.createTextNode("x"));
}
var offsetHeight = lineDiv.clientHeight;
if (offsetHeight == cachedHeightFor) return cachedHeight;
cachedHeightFor = offsetHeight;
removeChildrenAndAdd(measure, measurePre.cloneNode(true));
cachedHeight = measure.firstChild.offsetHeight / 50 || 1;
removeChildren(measure);
return cachedHeight;
}
var cachedWidth, cachedWidthFor = 0;
function charWidth() {
if (scroller.clientWidth == cachedWidthFor) return cachedWidth;
cachedWidthFor = scroller.clientWidth;
var anchor = elt("span", "x");
var pre = elt("pre", [anchor]);
removeChildrenAndAdd(measure, pre);
return (cachedWidth = anchor.offsetWidth || 10);
}
function paddingTop() {return lineSpace.offsetTop;}
function paddingLeft() {return lineSpace.offsetLeft;}
function posFromMouse(e, liberal) {
var offW = eltOffset(scroller, true), x, y;
// Fails unpredictably on IE[67] when mouse is dragged around quickly.
try { x = e.clientX; y = e.clientY; } catch (e) { return null; }
// This is a mess of a heuristic to try and determine whether a
// scroll-bar was clicked or not, and to return null if one was
// (and !liberal).
if (!liberal && (x - offW.left > scroller.clientWidth || y - offW.top > scroller.clientHeight))
return null;
var offL = eltOffset(lineSpace, true);
return coordsChar(x - offL.left, y - offL.top);
}
var detectingSelectAll;
function onContextMenu(e) {
var pos = posFromMouse(e), scrollPos = scrollbar.scrollTop;
if (!pos || opera) return; // Opera is difficult.
if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to))
operation(setCursor)(pos.line, pos.ch);
var oldCSS = input.style.cssText;
inputDiv.style.position = "absolute";
input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
"px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: white; " +
"border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
focusInput();
resetInput(true);
// Adds "Select all" to context menu in FF
if (posEq(sel.from, sel.to)) input.value = prevInput = " ";
function rehide() {
inputDiv.style.position = "relative";
input.style.cssText = oldCSS;
if (ie_lt9) scrollbar.scrollTop = scrollPos;
slowPoll();
// Try to detect the user choosing select-all
if (input.selectionStart != null) {
clearTimeout(detectingSelectAll);
var extval = input.value = " " + (posEq(sel.from, sel.to) ? "" : input.value), i = 0;
prevInput = " ";
input.selectionStart = 1; input.selectionEnd = extval.length;
detectingSelectAll = setTimeout(function poll(){
if (prevInput == " " && input.selectionStart == 0)
operation(commands.selectAll)(instance);
else if (i++ < 10) detectingSelectAll = setTimeout(poll, 500);
else resetInput();
}, 200);
}
}
if (gecko) {
e_stop(e);
var mouseup = connect(window, "mouseup", function() {
mouseup();
setTimeout(rehide, 20);
}, true);
} else {
setTimeout(rehide, 50);
}
}
// Cursor-blinking
function restartBlink() {
clearInterval(blinker);
var on = true;
cursor.style.visibility = "";
blinker = setInterval(function() {
cursor.style.visibility = (on = !on) ? "" : "hidden";
}, options.cursorBlinkRate);
}
var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"};
function matchBrackets(autoclear) {
var head = sel.inverted ? sel.from : sel.to, line = getLine(head.line), pos = head.ch - 1;
var match = (pos >= 0 && matching[line.text.charAt(pos)]) || matching[line.text.charAt(++pos)];
if (!match) return;
var ch = match.charAt(0), forward = match.charAt(1) == ">", d = forward ? 1 : -1, st = line.styles;
for (var off = pos + 1, i = 0, e = st.length; i < e; i+=2)
if ((off -= st[i].length) <= 0) {var style = st[i+1]; break;}
var stack = [line.text.charAt(pos)], re = /[(){}[\]]/;
function scan(line, from, to) {
if (!line.text) return;
var st = line.styles, pos = forward ? 0 : line.text.length - 1, cur;
for (var i = forward ? 0 : st.length - 2, e = forward ? st.length : -2; i != e; i += 2*d) {
var text = st[i];
if (st[i+1] != style) {pos += d * text.length; continue;}
for (var j = forward ? 0 : text.length - 1, te = forward ? text.length : -1; j != te; j += d, pos+=d) {
if (pos >= from && pos < to && re.test(cur = text.charAt(j))) {
var match = matching[cur];
if (match.charAt(1) == ">" == forward) stack.push(cur);
else if (stack.pop() != match.charAt(0)) return {pos: pos, match: false};
else if (!stack.length) return {pos: pos, match: true};
}
}
}
}
for (var i = head.line, e = forward ? Math.min(i + 100, doc.size) : Math.max(-1, i - 100); i != e; i+=d) {
var line = getLine(i), first = i == head.line;
var found = scan(line, first && forward ? pos + 1 : 0, first && !forward ? pos : line.text.length);
if (found) break;
}
if (!found) found = {pos: null, match: false};
var style = found.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket";
var one = markText({line: head.line, ch: pos}, {line: head.line, ch: pos+1}, style),
two = found.pos != null && markText({line: i, ch: found.pos}, {line: i, ch: found.pos + 1}, style);
var clear = operation(function(){one.clear(); two && two.clear();});
if (autoclear) setTimeout(clear, 800);
else bracketHighlighted = clear;
}
// Finds the line to start with when starting a parse. Tries to
// find a line with a stateAfter, so that it can start with a
// valid state. If that fails, it returns the line with the
// smallest indentation, which tends to need the least context to
// parse correctly.
function findStartLine(n) {
var minindent, minline;
for (var search = n, lim = n - 40; search > lim; --search) {
if (search == 0) return 0;
var line = getLine(search-1);
if (line.stateAfter) return search;
var indented = line.indentation(options.tabSize);
if (minline == null || minindent > indented) {
minline = search - 1;
minindent = indented;
}
}
return minline;
}
function getStateBefore(n) {
var pos = findStartLine(n), state = pos && getLine(pos-1).stateAfter;
if (!state) state = startState(mode);
else state = copyState(mode, state);
doc.iter(pos, n, function(line) {
line.process(mode, state, options.tabSize);
line.stateAfter = (pos == n - 1 || pos % 5 == 0) ? copyState(mode, state) : null;
});
return state;
}
function highlightWorker() {
if (frontier >= showingTo) return;
var end = +new Date + options.workTime, state = copyState(mode, getStateBefore(frontier));
var startFrontier = frontier;
doc.iter(frontier, showingTo, function(line) {
if (frontier >= showingFrom) { // Visible
line.highlight(mode, state, options.tabSize);
line.stateAfter = copyState(mode, state);
} else {
line.process(mode, state, options.tabSize);
line.stateAfter = frontier % 5 == 0 ? copyState(mode, state) : null;
}
++frontier;
if (+new Date > end) {
startWorker(options.workDelay);
return true;
}
});
if (showingTo > startFrontier && frontier >= showingFrom)
operation(function() {changes.push({from: startFrontier, to: frontier});})();
}
function startWorker(time) {
if (frontier < showingTo)
highlight.set(time, highlightWorker);
}
// Operations are used to wrap changes in such a way that each
// change won't have to update the cursor and display (which would
// be awkward, slow, and error-prone), but instead updates are
// batched and then all combined and executed at once.
function startOperation() {
updateInput = userSelChange = textChanged = null;
changes = []; selectionChanged = false; callbacks = [];
}
function endOperation() {
if (updateMaxLine) computeMaxLength();
if (maxLineChanged && !options.lineWrapping) {
var cursorWidth = widthForcer.offsetWidth, left = measureLine(maxLine, maxLine.text.length).left;
if (!ie_lt8) {
widthForcer.style.left = left + "px";
lineSpace.style.minWidth = (left + cursorWidth) + "px";
}
maxLineChanged = false;
}
var newScrollPos, updated;
if (selectionChanged) {
var coords = calculateCursorCoords();
newScrollPos = calculateScrollPos(coords.x, coords.y, coords.x, coords.yBot);
}
if (changes.length || newScrollPos && newScrollPos.scrollTop != null)
updated = updateDisplay(changes, true, newScrollPos && newScrollPos.scrollTop);
if (!updated) {
if (selectionChanged) updateSelection();
if (gutterDirty) updateGutter();
}
if (newScrollPos) scrollCursorIntoView();
if (selectionChanged) restartBlink();
if (focused && (updateInput === true || (updateInput !== false && selectionChanged)))
resetInput(userSelChange);
if (selectionChanged && options.matchBrackets)
setTimeout(operation(function() {
if (bracketHighlighted) {bracketHighlighted(); bracketHighlighted = null;}
if (posEq(sel.from, sel.to)) matchBrackets(false);
}), 20);
var sc = selectionChanged, cbs = callbacks; // these can be reset by callbacks
if (textChanged && options.onChange && instance)
options.onChange(instance, textChanged);
if (sc && options.onCursorActivity)
options.onCursorActivity(instance);
for (var i = 0; i < cbs.length; ++i) cbs[i](instance);
if (updated && options.onUpdate) options.onUpdate(instance);
}
var nestedOperation = 0;
function operation(f) {
return function() {
if (!nestedOperation++) startOperation();
try {var result = f.apply(this, arguments);}
finally {if (!--nestedOperation) endOperation();}
return result;
};
}
function compoundChange(f) {
history.startCompound();
try { return f(); } finally { history.endCompound(); }
}
for (var ext in extensions)
if (extensions.propertyIsEnumerable(ext) &&
!instance.propertyIsEnumerable(ext))
instance[ext] = extensions[ext];
for (var i = 0; i < initHooks.length; ++i) initHooks[i](instance);
return instance;
} // (end of function CodeMirror)
// The default configuration options.
CodeMirror.defaults = {
value: "",
mode: null,
theme: "default",
indentUnit: 2,
indentWithTabs: false,
smartIndent: true,
tabSize: 4,
keyMap: "default",
extraKeys: null,
electricChars: true,
autoClearEmptyLines: false,
onKeyEvent: null,
onDragEvent: null,
lineWrapping: false,
lineNumbers: false,
gutter: false,
fixedGutter: false,
firstLineNumber: 1,
readOnly: false,
dragDrop: true,
onChange: null,
onCursorActivity: null,
onViewportChange: null,
onGutterClick: null,
onUpdate: null,
onFocus: null, onBlur: null, onScroll: null,
matchBrackets: false,
cursorBlinkRate: 530,
workTime: 100,
workDelay: 200,
pollInterval: 100,
undoDepth: 40,
tabindex: null,
autofocus: null,
lineNumberFormatter: function(integer) { return integer; }
};
var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
var mac = ios || /Mac/.test(navigator.platform);
var win = /Win/.test(navigator.platform);
// Known modes, by name and by MIME
var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
CodeMirror.defineMode = function(name, mode) {
if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
if (arguments.length > 2) {
mode.dependencies = [];
for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]);
}
modes[name] = mode;
};
CodeMirror.defineMIME = function(mime, spec) {
mimeModes[mime] = spec;
};
CodeMirror.resolveMode = function(spec) {
if (typeof spec == "string" && mimeModes.hasOwnProperty(spec))
spec = mimeModes[spec];
else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec))
return CodeMirror.resolveMode("application/xml");
if (typeof spec == "string") return {name: spec};
else return spec || {name: "null"};
};
CodeMirror.getMode = function(options, spec) {
var spec = CodeMirror.resolveMode(spec);
var mfactory = modes[spec.name];
if (!mfactory) return CodeMirror.getMode(options, "text/plain");
var modeObj = mfactory(options, spec);
if (modeExtensions.hasOwnProperty(spec.name)) {
var exts = modeExtensions[spec.name];
for (var prop in exts) if (exts.hasOwnProperty(prop)) modeObj[prop] = exts[prop];
}
modeObj.name = spec.name;
return modeObj;
};
CodeMirror.listModes = function() {
var list = [];
for (var m in modes)
if (modes.propertyIsEnumerable(m)) list.push(m);
return list;
};
CodeMirror.listMIMEs = function() {
var list = [];
for (var m in mimeModes)
if (mimeModes.propertyIsEnumerable(m)) list.push({mime: m, mode: mimeModes[m]});
return list;
};
var extensions = CodeMirror.extensions = {};
CodeMirror.defineExtension = function(name, func) {
extensions[name] = func;
};
var initHooks = [];
CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
var modeExtensions = CodeMirror.modeExtensions = {};
CodeMirror.extendMode = function(mode, properties) {
var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
for (var prop in properties) if (properties.hasOwnProperty(prop))
exts[prop] = properties[prop];
};
var commands = CodeMirror.commands = {
selectAll: function(cm) {cm.setSelection({line: 0, ch: 0}, {line: cm.lineCount() - 1});},
killLine: function(cm) {
var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to);
if (!sel && cm.getLine(from.line).length == from.ch) cm.replaceRange("", from, {line: from.line + 1, ch: 0});
else cm.replaceRange("", from, sel ? to : {line: from.line});
},
deleteLine: function(cm) {var l = cm.getCursor().line; cm.replaceRange("", {line: l, ch: 0}, {line: l});},
undo: function(cm) {cm.undo();},
redo: function(cm) {cm.redo();},
goDocStart: function(cm) {cm.setCursor(0, 0, true);},
goDocEnd: function(cm) {cm.setSelection({line: cm.lineCount() - 1}, null, true);},
goLineStart: function(cm) {cm.setCursor(cm.getCursor().line, 0, true);},
goLineStartSmart: function(cm) {
var cur = cm.getCursor();
var text = cm.getLine(cur.line), firstNonWS = Math.max(0, text.search(/\S/));
cm.setCursor(cur.line, cur.ch <= firstNonWS && cur.ch ? 0 : firstNonWS, true);
},
goLineEnd: function(cm) {cm.setSelection({line: cm.getCursor().line}, null, true);},
goLineUp: function(cm) {cm.moveV(-1, "line");},
goLineDown: function(cm) {cm.moveV(1, "line");},
goPageUp: function(cm) {cm.moveV(-1, "page");},
goPageDown: function(cm) {cm.moveV(1, "page");},
goCharLeft: function(cm) {cm.moveH(-1, "char");},
goCharRight: function(cm) {cm.moveH(1, "char");},
goColumnLeft: function(cm) {cm.moveH(-1, "column");},
goColumnRight: function(cm) {cm.moveH(1, "column");},
goWordLeft: function(cm) {cm.moveH(-1, "word");},
goWordRight: function(cm) {cm.moveH(1, "word");},
delCharLeft: function(cm) {cm.deleteH(-1, "char");},
delCharRight: function(cm) {cm.deleteH(1, "char");},
delWordLeft: function(cm) {cm.deleteH(-1, "word");},
delWordRight: function(cm) {cm.deleteH(1, "word");},
indentAuto: function(cm) {cm.indentSelection("smart");},
indentMore: function(cm) {cm.indentSelection("add");},
indentLess: function(cm) {cm.indentSelection("subtract");},
insertTab: function(cm) {cm.replaceSelection("\t", "end");},
defaultTab: function(cm) {
if (cm.somethingSelected()) cm.indentSelection("add");
else cm.replaceSelection("\t", "end");
},
transposeChars: function(cm) {
var cur = cm.getCursor(), line = cm.getLine(cur.line);
if (cur.ch > 0 && cur.ch < line.length - 1)
cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1),
{line: cur.line, ch: cur.ch - 1}, {line: cur.line, ch: cur.ch + 1});
},
newlineAndIndent: function(cm) {
cm.replaceSelection("\n", "end");
cm.indentLine(cm.getCursor().line);
},
toggleOverwrite: function(cm) {cm.toggleOverwrite();}
};
var keyMap = CodeMirror.keyMap = {};
keyMap.basic = {
"Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
"End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
"Delete": "delCharRight", "Backspace": "delCharLeft", "Tab": "defaultTab", "Shift-Tab": "indentAuto",
"Enter": "newlineAndIndent", "Insert": "toggleOverwrite"
};
// Note that the save and find-related commands aren't defined by
// default. Unknown commands are simply ignored.
keyMap.pcDefault = {
"Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
"Ctrl-Home": "goDocStart", "Alt-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd",
"Ctrl-Left": "goWordLeft", "Ctrl-Right": "goWordRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
"Ctrl-Backspace": "delWordLeft", "Ctrl-Delete": "delWordRight", "Ctrl-S": "save", "Ctrl-F": "find",
"Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
"Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
fallthrough: "basic"
};
keyMap.macDefault = {
"Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
"Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goWordLeft",
"Alt-Right": "goWordRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delWordLeft",
"Ctrl-Alt-Backspace": "delWordRight", "Alt-Delete": "delWordRight", "Cmd-S": "save", "Cmd-F": "find",
"Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
"Cmd-[": "indentLess", "Cmd-]": "indentMore",
fallthrough: ["basic", "emacsy"]
};
keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
keyMap.emacsy = {
"Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
"Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
"Ctrl-V": "goPageUp", "Shift-Ctrl-V": "goPageDown", "Ctrl-D": "delCharRight", "Ctrl-H": "delCharLeft",
"Alt-D": "delWordRight", "Alt-Backspace": "delWordLeft", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
};
function getKeyMap(val) {
if (typeof val == "string") return keyMap[val];
else return val;
}
function lookupKey(name, extraMap, map, handle, stop) {
function lookup(map) {
map = getKeyMap(map);
var found = map[name];
if (found === false) {
if (stop) stop();
return true;
}
if (found != null && handle(found)) return true;
if (map.nofallthrough) {
if (stop) stop();
return true;
}
var fallthrough = map.fallthrough;
if (fallthrough == null) return false;
if (Object.prototype.toString.call(fallthrough) != "[object Array]")
return lookup(fallthrough);
for (var i = 0, e = fallthrough.length; i < e; ++i) {
if (lookup(fallthrough[i])) return true;
}
return false;
}
if (extraMap && lookup(extraMap)) return true;
return lookup(map);
}
function isModifierKey(event) {
var name = keyNames[e_prop(event, "keyCode")];
return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
}
CodeMirror.isModifierKey = isModifierKey;
CodeMirror.fromTextArea = function(textarea, options) {
if (!options) options = {};
options.value = textarea.value;
if (!options.tabindex && textarea.tabindex)
options.tabindex = textarea.tabindex;
// Set autofocus to true if this textarea is focused, or if it has
// autofocus and no other element is focused.
if (options.autofocus == null) {
var hasFocus = document.body;
// doc.activeElement occasionally throws on IE
try { hasFocus = document.activeElement; } catch(e) {}
options.autofocus = hasFocus == textarea ||
textarea.getAttribute("autofocus") != null && hasFocus == document.body;
}
function save() {textarea.value = instance.getValue();}
if (textarea.form) {
// Deplorable hack to make the submit method do the right thing.
var rmSubmit = connect(textarea.form, "submit", save, true);
if (typeof textarea.form.submit == "function") {
var realSubmit = textarea.form.submit;
textarea.form.submit = function wrappedSubmit() {
save();
textarea.form.submit = realSubmit;
textarea.form.submit();
textarea.form.submit = wrappedSubmit;
};
}
}
textarea.style.display = "none";
var instance = CodeMirror(function(node) {
textarea.parentNode.insertBefore(node, textarea.nextSibling);
}, options);
instance.save = save;
instance.getTextArea = function() { return textarea; };
instance.toTextArea = function() {
save();
textarea.parentNode.removeChild(instance.getWrapperElement());
textarea.style.display = "";
if (textarea.form) {
rmSubmit();
if (typeof textarea.form.submit == "function")
textarea.form.submit = realSubmit;
}
};
return instance;
};
var gecko = /gecko\/\d{7}/i.test(navigator.userAgent);
var ie = /MSIE \d/.test(navigator.userAgent);
var ie_lt8 = /MSIE [1-7]\b/.test(navigator.userAgent);
var ie_lt9 = /MSIE [1-8]\b/.test(navigator.userAgent);
var quirksMode = ie && document.documentMode == 5;
var webkit = /WebKit\//.test(navigator.userAgent);
var chrome = /Chrome\//.test(navigator.userAgent);
var opera = /Opera\//.test(navigator.userAgent);
var safari = /Apple Computer/.test(navigator.vendor);
var khtml = /KHTML\//.test(navigator.userAgent);
var mac_geLion = /Mac OS X 10\D([7-9]|\d\d)\D/.test(navigator.userAgent);
// Utility functions for working with state. Exported because modes
// sometimes need to do this.
function copyState(mode, state) {
if (state === true) return state;
if (mode.copyState) return mode.copyState(state);
var nstate = {};
for (var n in state) {
var val = state[n];
if (val instanceof Array) val = val.concat([]);
nstate[n] = val;
}
return nstate;
}
CodeMirror.copyState = copyState;
function startState(mode, a1, a2) {
return mode.startState ? mode.startState(a1, a2) : true;
}
CodeMirror.startState = startState;
CodeMirror.innerMode = function(mode, state) {
while (mode.innerMode) {
var info = mode.innerMode(state);
state = info.state;
mode = info.mode;
}
return info || {mode: mode, state: state};
};
// The character stream used by a mode's parser.
function StringStream(string, tabSize) {
this.pos = this.start = 0;
this.string = string;
this.tabSize = tabSize || 8;
}
StringStream.prototype = {
eol: function() {return this.pos >= this.string.length;},
sol: function() {return this.pos == 0;},
peek: function() {return this.string.charAt(this.pos) || undefined;},
next: function() {
if (this.pos < this.string.length)
return this.string.charAt(this.pos++);
},
eat: function(match) {
var ch = this.string.charAt(this.pos);
if (typeof match == "string") var ok = ch == match;
else var ok = ch && (match.test ? match.test(ch) : match(ch));
if (ok) {++this.pos; return ch;}
},
eatWhile: function(match) {
var start = this.pos;
while (this.eat(match)){}
return this.pos > start;
},
eatSpace: function() {
var start = this.pos;
while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
return this.pos > start;
},
skipToEnd: function() {this.pos = this.string.length;},
skipTo: function(ch) {
var found = this.string.indexOf(ch, this.pos);
if (found > -1) {this.pos = found; return true;}
},
backUp: function(n) {this.pos -= n;},
column: function() {return countColumn(this.string, this.start, this.tabSize);},
indentation: function() {return countColumn(this.string, null, this.tabSize);},
match: function(pattern, consume, caseInsensitive) {
if (typeof pattern == "string") {
var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
if (cased(this.string).indexOf(cased(pattern), this.pos) == this.pos) {
if (consume !== false) this.pos += pattern.length;
return true;
}
} else {
var match = this.string.slice(this.pos).match(pattern);
if (match && match.index > 0) return null;
if (match && consume !== false) this.pos += match[0].length;
return match;
}
},
current: function(){return this.string.slice(this.start, this.pos);}
};
CodeMirror.StringStream = StringStream;
function MarkedSpan(from, to, marker) {
this.from = from; this.to = to; this.marker = marker;
}
function getMarkedSpanFor(spans, marker) {
if (spans) for (var i = 0; i < spans.length; ++i) {
var span = spans[i];
if (span.marker == marker) return span;
}
}
function removeMarkedSpan(spans, span) {
var r;
for (var i = 0; i < spans.length; ++i)
if (spans[i] != span) (r || (r = [])).push(spans[i]);
return r;
}
function markedSpansBefore(old, startCh, endCh) {
if (old) for (var i = 0, nw; i < old.length; ++i) {
var span = old[i], marker = span.marker;
var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
if (startsBefore || marker.type == "bookmark" && span.from == startCh && span.from != endCh) {
var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
(nw || (nw = [])).push({from: span.from,
to: endsAfter ? null : span.to,
marker: marker});
}
}
return nw;
}
function markedSpansAfter(old, endCh) {
if (old) for (var i = 0, nw; i < old.length; ++i) {
var span = old[i], marker = span.marker;
var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
if (endsAfter || marker.type == "bookmark" && span.from == endCh) {
var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
(nw || (nw = [])).push({from: startsBefore ? null : span.from - endCh,
to: span.to == null ? null : span.to - endCh,
marker: marker});
}
}
return nw;
}
function updateMarkedSpans(oldFirst, oldLast, startCh, endCh, newText) {
if (!oldFirst && !oldLast) return newText;
// Get the spans that 'stick out' on both sides
var first = markedSpansBefore(oldFirst, startCh);
var last = markedSpansAfter(oldLast, endCh);
// Next, merge those two ends
var sameLine = newText.length == 1, offset = lst(newText).length + (sameLine ? startCh : 0);
if (first) {
// Fix up .to properties of first
for (var i = 0; i < first.length; ++i) {
var span = first[i];
if (span.to == null) {
var found = getMarkedSpanFor(last, span.marker);
if (!found) span.to = startCh;
else if (sameLine) span.to = found.to == null ? null : found.to + offset;
}
}
}
if (last) {
// Fix up .from in last (or move them into first in case of sameLine)
for (var i = 0; i < last.length; ++i) {
var span = last[i];
if (span.to != null) span.to += offset;
if (span.from == null) {
var found = getMarkedSpanFor(first, span.marker);
if (!found) {
span.from = offset;
if (sameLine) (first || (first = [])).push(span);
}
} else {
span.from += offset;
if (sameLine) (first || (first = [])).push(span);
}
}
}
var newMarkers = [newHL(newText[0], first)];
if (!sameLine) {
// Fill gap with whole-line-spans
var gap = newText.length - 2, gapMarkers;
if (gap > 0 && first)
for (var i = 0; i < first.length; ++i)
if (first[i].to == null)
(gapMarkers || (gapMarkers = [])).push({from: null, to: null, marker: first[i].marker});
for (var i = 0; i < gap; ++i)
newMarkers.push(newHL(newText[i+1], gapMarkers));
newMarkers.push(newHL(lst(newText), last));
}
return newMarkers;
}
// hl stands for history-line, a data structure that can be either a
// string (line without markers) or a {text, markedSpans} object.
function hlText(val) { return typeof val == "string" ? val : val.text; }
function hlSpans(val) {
if (typeof val == "string") return null;
var spans = val.markedSpans, out = null;
for (var i = 0; i < spans.length; ++i) {
if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
else if (out) out.push(spans[i]);
}
return !out ? spans : out.length ? out : null;
}
function newHL(text, spans) { return spans ? {text: text, markedSpans: spans} : text; }
function detachMarkedSpans(line) {
var spans = line.markedSpans;
if (!spans) return;
for (var i = 0; i < spans.length; ++i) {
var lines = spans[i].marker.lines;
var ix = indexOf(lines, line);
lines.splice(ix, 1);
}
line.markedSpans = null;
}
function attachMarkedSpans(line, spans) {
if (!spans) return;
for (var i = 0; i < spans.length; ++i)
var marker = spans[i].marker.lines.push(line);
line.markedSpans = spans;
}
// When measuring the position of the end of a line, different
// browsers require different approaches. If an empty span is added,
// many browsers report bogus offsets. Of those, some (Webkit,
// recent IE) will accept a space without moving the whole span to
// the next line when wrapping it, others work with a zero-width
// space.
var eolSpanContent = " ";
if (gecko || (ie && !ie_lt8)) eolSpanContent = "\u200b";
else if (opera) eolSpanContent = "";
// Line objects. These hold state related to a line, including
// highlighting info (the styles array).
function Line(text, markedSpans) {
this.text = text;
this.height = 1;
attachMarkedSpans(this, markedSpans);
}
Line.prototype = {
update: function(text, markedSpans) {
this.text = text;
this.stateAfter = this.styles = null;
detachMarkedSpans(this);
attachMarkedSpans(this, markedSpans);
},
// Run the given mode's parser over a line, update the styles
// array, which contains alternating fragments of text and CSS
// classes.
highlight: function(mode, state, tabSize) {
var stream = new StringStream(this.text, tabSize), st = this.styles || (this.styles = []);
var pos = st.length = 0;
if (this.text == "" && mode.blankLine) mode.blankLine(state);
while (!stream.eol()) {
var style = mode.token(stream, state), substr = stream.current();
stream.start = stream.pos;
if (pos && st[pos-1] == style) {
st[pos-2] += substr;
} else if (substr) {
st[pos++] = substr; st[pos++] = style;
}
// Give up when line is ridiculously long
if (stream.pos > 5000) {
st[pos++] = this.text.slice(stream.pos); st[pos++] = null;
break;
}
}
},
process: function(mode, state, tabSize) {
var stream = new StringStream(this.text, tabSize);
if (this.text == "" && mode.blankLine) mode.blankLine(state);
while (!stream.eol() && stream.pos <= 5000) {
mode.token(stream, state);
stream.start = stream.pos;
}
},
// Fetch the parser token for a given character. Useful for hacks
// that want to inspect the mode state (say, for completion).
getTokenAt: function(mode, state, tabSize, ch) {
var txt = this.text, stream = new StringStream(txt, tabSize);
while (stream.pos < ch && !stream.eol()) {
stream.start = stream.pos;
var style = mode.token(stream, state);
}
return {start: stream.start,
end: stream.pos,
string: stream.current(),
className: style || null,
state: state};
},
indentation: function(tabSize) {return countColumn(this.text, null, tabSize);},
// Produces an HTML fragment for the line, taking selection,
// marking, and highlighting into account.
getContent: function(tabSize, wrapAt, compensateForWrapping) {
var first = true, col = 0, specials = /[\t\u0000-\u0019\u200b\u2028\u2029\uFEFF]/g;
var pre = elt("pre");
function span_(html, text, style) {
if (!text) return;
// Work around a bug where, in some compat modes, IE ignores leading spaces
if (first && ie && text.charAt(0) == " ") text = "\u00a0" + text.slice(1);
first = false;
if (!specials.test(text)) {
col += text.length;
var content = document.createTextNode(text);
} else {
var content = document.createDocumentFragment(), pos = 0;
while (true) {
specials.lastIndex = pos;
var m = specials.exec(text);
var skipped = m ? m.index - pos : text.length - pos;
if (skipped) {
content.appendChild(document.createTextNode(text.slice(pos, pos + skipped)));
col += skipped;
}
if (!m) break;
pos += skipped + 1;
if (m[0] == "\t") {
var tabWidth = tabSize - col % tabSize;
content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
col += tabWidth;
} else {
var token = elt("span", "\u2022", "cm-invalidchar");
token.title = "\\u" + m[0].charCodeAt(0).toString(16);
content.appendChild(token);
col += 1;
}
}
}
if (style) html.appendChild(elt("span", [content], style));
else html.appendChild(content);
}
var span = span_;
if (wrapAt != null) {
var outPos = 0, anchor = pre.anchor = elt("span");
span = function(html, text, style) {
var l = text.length;
if (wrapAt >= outPos && wrapAt < outPos + l) {
var cut = wrapAt - outPos;
if (cut) {
span_(html, text.slice(0, cut), style);
// See comment at the definition of spanAffectsWrapping
if (compensateForWrapping) {
var view = text.slice(cut - 1, cut + 1);
if (spanAffectsWrapping.test(view)) html.appendChild(elt("wbr"));
else if (!ie_lt8 && /\w\w/.test(view)) html.appendChild(document.createTextNode("\u200d"));
}
}
html.appendChild(anchor);
span_(anchor, opera ? text.slice(cut, cut + 1) : text.slice(cut), style);
if (opera) span_(html, text.slice(cut + 1), style);
wrapAt--;
outPos += l;
} else {
outPos += l;
span_(html, text, style);
if (outPos == wrapAt && outPos == len) {
setTextContent(anchor, eolSpanContent);
html.appendChild(anchor);
}
// Stop outputting HTML when gone sufficiently far beyond measure
else if (outPos > wrapAt + 10 && /\s/.test(text)) span = function(){};
}
};
}
var st = this.styles, allText = this.text, marked = this.markedSpans;
var len = allText.length;
function styleToClass(style) {
if (!style) return null;
return "cm-" + style.replace(/ +/g, " cm-");
}
if (!allText && wrapAt == null) {
span(pre, " ");
} else if (!marked || !marked.length) {
for (var i = 0, ch = 0; ch < len; i+=2) {
var str = st[i], style = st[i+1], l = str.length;
if (ch + l > len) str = str.slice(0, len - ch);
ch += l;
span(pre, str, styleToClass(style));
}
} else {
marked.sort(function(a, b) { return a.from - b.from; });
var pos = 0, i = 0, text = "", style, sg = 0;
var nextChange = marked[0].from || 0, marks = [], markpos = 0;
var advanceMarks = function() {
var m;
while (markpos < marked.length &&
((m = marked[markpos]).from == pos || m.from == null)) {
if (m.marker.type == "range") marks.push(m);
++markpos;
}
nextChange = markpos < marked.length ? marked[markpos].from : Infinity;
for (var i = 0; i < marks.length; ++i) {
var to = marks[i].to;
if (to == null) to = Infinity;
if (to == pos) marks.splice(i--, 1);
else nextChange = Math.min(to, nextChange);
}
};
var m = 0;
while (pos < len) {
if (nextChange == pos) advanceMarks();
var upto = Math.min(len, nextChange);
while (true) {
if (text) {
var end = pos + text.length;
var appliedStyle = style;
for (var j = 0; j < marks.length; ++j) {
var mark = marks[j];
appliedStyle = (appliedStyle ? appliedStyle + " " : "") + mark.marker.style;
if (mark.marker.endStyle && mark.to === Math.min(end, upto)) appliedStyle += " " + mark.marker.endStyle;
if (mark.marker.startStyle && mark.from === pos) appliedStyle += " " + mark.marker.startStyle;
}
span(pre, end > upto ? text.slice(0, upto - pos) : text, appliedStyle);
if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
pos = end;
}
text = st[i++]; style = styleToClass(st[i++]);
}
}
}
return pre;
},
cleanUp: function() {
this.parent = null;
detachMarkedSpans(this);
}
};
// Data structure that holds the sequence of lines.
function LeafChunk(lines) {
this.lines = lines;
this.parent = null;
for (var i = 0, e = lines.length, height = 0; i < e; ++i) {
lines[i].parent = this;
height += lines[i].height;
}
this.height = height;
}
LeafChunk.prototype = {
chunkSize: function() { return this.lines.length; },
remove: function(at, n, callbacks) {
for (var i = at, e = at + n; i < e; ++i) {
var line = this.lines[i];
this.height -= line.height;
line.cleanUp();
if (line.handlers)
for (var j = 0; j < line.handlers.length; ++j) callbacks.push(line.handlers[j]);
}
this.lines.splice(at, n);
},
collapse: function(lines) {
lines.splice.apply(lines, [lines.length, 0].concat(this.lines));
},
insertHeight: function(at, lines, height) {
this.height += height;
this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
for (var i = 0, e = lines.length; i < e; ++i) lines[i].parent = this;
},
iterN: function(at, n, op) {
for (var e = at + n; at < e; ++at)
if (op(this.lines[at])) return true;
}
};
function BranchChunk(children) {
this.children = children;
var size = 0, height = 0;
for (var i = 0, e = children.length; i < e; ++i) {
var ch = children[i];
size += ch.chunkSize(); height += ch.height;
ch.parent = this;
}
this.size = size;
this.height = height;
this.parent = null;
}
BranchChunk.prototype = {
chunkSize: function() { return this.size; },
remove: function(at, n, callbacks) {
this.size -= n;
for (var i = 0; i < this.children.length; ++i) {
var child = this.children[i], sz = child.chunkSize();
if (at < sz) {
var rm = Math.min(n, sz - at), oldHeight = child.height;
child.remove(at, rm, callbacks);
this.height -= oldHeight - child.height;
if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
if ((n -= rm) == 0) break;
at = 0;
} else at -= sz;
}
if (this.size - n < 25) {
var lines = [];
this.collapse(lines);
this.children = [new LeafChunk(lines)];
this.children[0].parent = this;
}
},
collapse: function(lines) {
for (var i = 0, e = this.children.length; i < e; ++i) this.children[i].collapse(lines);
},
insert: function(at, lines) {
var height = 0;
for (var i = 0, e = lines.length; i < e; ++i) height += lines[i].height;
this.insertHeight(at, lines, height);
},
insertHeight: function(at, lines, height) {
this.size += lines.length;
this.height += height;
for (var i = 0, e = this.children.length; i < e; ++i) {
var child = this.children[i], sz = child.chunkSize();
if (at <= sz) {
child.insertHeight(at, lines, height);
if (child.lines && child.lines.length > 50) {
while (child.lines.length > 50) {
var spilled = child.lines.splice(child.lines.length - 25, 25);
var newleaf = new LeafChunk(spilled);
child.height -= newleaf.height;
this.children.splice(i + 1, 0, newleaf);
newleaf.parent = this;
}
this.maybeSpill();
}
break;
}
at -= sz;
}
},
maybeSpill: function() {
if (this.children.length <= 10) return;
var me = this;
do {
var spilled = me.children.splice(me.children.length - 5, 5);
var sibling = new BranchChunk(spilled);
if (!me.parent) { // Become the parent node
var copy = new BranchChunk(me.children);
copy.parent = me;
me.children = [copy, sibling];
me = copy;
} else {
me.size -= sibling.size;
me.height -= sibling.height;
var myIndex = indexOf(me.parent.children, me);
me.parent.children.splice(myIndex + 1, 0, sibling);
}
sibling.parent = me.parent;
} while (me.children.length > 10);
me.parent.maybeSpill();
},
iter: function(from, to, op) { this.iterN(from, to - from, op); },
iterN: function(at, n, op) {
for (var i = 0, e = this.children.length; i < e; ++i) {
var child = this.children[i], sz = child.chunkSize();
if (at < sz) {
var used = Math.min(n, sz - at);
if (child.iterN(at, used, op)) return true;
if ((n -= used) == 0) break;
at = 0;
} else at -= sz;
}
}
};
function getLineAt(chunk, n) {
while (!chunk.lines) {
for (var i = 0;; ++i) {
var child = chunk.children[i], sz = child.chunkSize();
if (n < sz) { chunk = child; break; }
n -= sz;
}
}
return chunk.lines[n];
}
function lineNo(line) {
if (line.parent == null) return null;
var cur = line.parent, no = indexOf(cur.lines, line);
for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
for (var i = 0, e = chunk.children.length; ; ++i) {
if (chunk.children[i] == cur) break;
no += chunk.children[i].chunkSize();
}
}
return no;
}
function lineAtHeight(chunk, h) {
var n = 0;
outer: do {
for (var i = 0, e = chunk.children.length; i < e; ++i) {
var child = chunk.children[i], ch = child.height;
if (h < ch) { chunk = child; continue outer; }
h -= ch;
n += child.chunkSize();
}
return n;
} while (!chunk.lines);
for (var i = 0, e = chunk.lines.length; i < e; ++i) {
var line = chunk.lines[i], lh = line.height;
if (h < lh) break;
h -= lh;
}
return n + i;
}
function heightAtLine(chunk, n) {
var h = 0;
outer: do {
for (var i = 0, e = chunk.children.length; i < e; ++i) {
var child = chunk.children[i], sz = child.chunkSize();
if (n < sz) { chunk = child; continue outer; }
n -= sz;
h += child.height;
}
return h;
} while (!chunk.lines);
for (var i = 0; i < n; ++i) h += chunk.lines[i].height;
return h;
}
// The history object 'chunks' changes that are made close together
// and at almost the same time into bigger undoable units.
function History() {
this.time = 0;
this.done = []; this.undone = [];
this.compound = 0;
this.closed = false;
}
History.prototype = {
addChange: function(start, added, old) {
this.undone.length = 0;
var time = +new Date, cur = lst(this.done), last = cur && lst(cur);
var dtime = time - this.time;
if (cur && !this.closed && this.compound) {
cur.push({start: start, added: added, old: old});
} else if (dtime > 400 || !last || this.closed ||
last.start > start + old.length || last.start + last.added < start) {
this.done.push([{start: start, added: added, old: old}]);
this.closed = false;
} else {
var startBefore = Math.max(0, last.start - start),
endAfter = Math.max(0, (start + old.length) - (last.start + last.added));
for (var i = startBefore; i > 0; --i) last.old.unshift(old[i - 1]);
for (var i = endAfter; i > 0; --i) last.old.push(old[old.length - i]);
if (startBefore) last.start = start;
last.added += added - (old.length - startBefore - endAfter);
}
this.time = time;
},
startCompound: function() {
if (!this.compound++) this.closed = true;
},
endCompound: function() {
if (!--this.compound) this.closed = true;
}
};
function stopMethod() {e_stop(this);}
// Ensure an event has a stop method.
function addStop(event) {
if (!event.stop) event.stop = stopMethod;
return event;
}
function e_preventDefault(e) {
if (e.preventDefault) e.preventDefault();
else e.returnValue = false;
}
function e_stopPropagation(e) {
if (e.stopPropagation) e.stopPropagation();
else e.cancelBubble = true;
}
function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
CodeMirror.e_stop = e_stop;
CodeMirror.e_preventDefault = e_preventDefault;
CodeMirror.e_stopPropagation = e_stopPropagation;
function e_target(e) {return e.target || e.srcElement;}
function e_button(e) {
var b = e.which;
if (b == null) {
if (e.button & 1) b = 1;
else if (e.button & 2) b = 3;
else if (e.button & 4) b = 2;
}
if (mac && e.ctrlKey && b == 1) b = 3;
return b;
}
// Allow 3rd-party code to override event properties by adding an override
// object to an event object.
function e_prop(e, prop) {
var overridden = e.override && e.override.hasOwnProperty(prop);
return overridden ? e.override[prop] : e[prop];
}
// Event handler registration. If disconnect is true, it'll return a
// function that unregisters the handler.
function connect(node, type, handler, disconnect) {
if (typeof node.addEventListener == "function") {
node.addEventListener(type, handler, false);
if (disconnect) return function() {node.removeEventListener(type, handler, false);};
} else {
var wrapHandler = function(event) {handler(event || window.event);};
node.attachEvent("on" + type, wrapHandler);
if (disconnect) return function() {node.detachEvent("on" + type, wrapHandler);};
}
}
CodeMirror.connect = connect;
function Delayed() {this.id = null;}
Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}};
var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
// Detect drag-and-drop
var dragAndDrop = function() {
// There is *some* kind of drag-and-drop support in IE6-8, but I
// couldn't get it to work yet.
if (ie_lt9) return false;
var div = elt('div');
return "draggable" in div || "dragDrop" in div;
}();
// Feature-detect whether newlines in textareas are converted to \r\n
var lineSep = function () {
var te = elt("textarea");
te.value = "foo\nbar";
if (te.value.indexOf("\r") > -1) return "\r\n";
return "\n";
}();
// For a reason I have yet to figure out, some browsers disallow
// word wrapping between certain characters *only* if a new inline
// element is started between them. This makes it hard to reliably
// measure the position of things, since that requires inserting an
// extra span. This terribly fragile set of regexps matches the
// character combinations that suffer from this phenomenon on the
// various browsers.
var spanAffectsWrapping = /^$/; // Won't match any two-character string
if (gecko) spanAffectsWrapping = /$'/;
else if (safari) spanAffectsWrapping = /\-[^ \-?]|\?[^ !'\"\),.\-\/:;\?\]\}]/;
else if (chrome) spanAffectsWrapping = /\-[^ \-\.?]|\?[^ \-\.?\]\}:;!'\"\),\/]|[\.!\"#&%\)*+,:;=>\]|\}~][\(\{\[<]|\$'/;
// Counts the column offset in a string, taking tabs into account.
// Used mostly to find indentation.
function countColumn(string, end, tabSize) {
if (end == null) {
end = string.search(/[^\s\u00a0]/);
if (end == -1) end = string.length;
}
for (var i = 0, n = 0; i < end; ++i) {
if (string.charAt(i) == "\t") n += tabSize - (n % tabSize);
else ++n;
}
return n;
}
function eltOffset(node, screen) {
// Take the parts of bounding client rect that we are interested in so we are able to edit if need be,
// since the returned value cannot be changed externally (they are kept in sync as the element moves within the page)
try { var box = node.getBoundingClientRect(); box = { top: box.top, left: box.left }; }
catch(e) { box = {top: 0, left: 0}; }
if (!screen) {
// Get the toplevel scroll, working around browser differences.
if (window.pageYOffset == null) {
var t = document.documentElement || document.body.parentNode;
if (t.scrollTop == null) t = document.body;
box.top += t.scrollTop; box.left += t.scrollLeft;
} else {
box.top += window.pageYOffset; box.left += window.pageXOffset;
}
}
return box;
}
function eltText(node) {
return node.textContent || node.innerText || node.nodeValue || "";
}
var spaceStrs = [""];
function spaceStr(n) {
while (spaceStrs.length <= n)
spaceStrs.push(lst(spaceStrs) + " ");
return spaceStrs[n];
}
function lst(arr) { return arr[arr.length-1]; }
function selectInput(node) {
if (ios) { // Mobile Safari apparently has a bug where select() is broken.
node.selectionStart = 0;
node.selectionEnd = node.value.length;
} else node.select();
}
// Operations on {line, ch} objects.
function posEq(a, b) {return a.line == b.line && a.ch == b.ch;}
function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);}
function copyPos(x) {return {line: x.line, ch: x.ch};}
function elt(tag, content, className, style) {
var e = document.createElement(tag);
if (className) e.className = className;
if (style) e.style.cssText = style;
if (typeof content == "string") setTextContent(e, content);
else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
return e;
}
function removeChildren(e) {
e.innerHTML = "";
return e;
}
function removeChildrenAndAdd(parent, e) {
removeChildren(parent).appendChild(e);
}
function setTextContent(e, str) {
if (ie_lt9) {
e.innerHTML = "";
e.appendChild(document.createTextNode(str));
} else e.textContent = str;
}
// Used to position the cursor after an undo/redo by finding the
// last edited character.
function editEnd(from, to) {
if (!to) return 0;
if (!from) return to.length;
for (var i = from.length, j = to.length; i >= 0 && j >= 0; --i, --j)
if (from.charAt(i) != to.charAt(j)) break;
return j + 1;
}
function indexOf(collection, elt) {
if (collection.indexOf) return collection.indexOf(elt);
for (var i = 0, e = collection.length; i < e; ++i)
if (collection[i] == elt) return i;
return -1;
}
function isWordChar(ch) {
return /\w/.test(ch) || ch.toUpperCase() != ch.toLowerCase() || /[\u4E00-\u9FA5]/.test(ch);
}
// See if "".split is the broken IE version, if so, provide an
// alternative way to split lines.
var splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
var pos = 0, result = [], l = string.length;
while (pos <= l) {
var nl = string.indexOf("\n", pos);
if (nl == -1) nl = string.length;
var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
var rt = line.indexOf("\r");
if (rt != -1) {
result.push(line.slice(0, rt));
pos += rt + 1;
} else {
result.push(line);
pos = nl + 1;
}
}
return result;
} : function(string){return string.split(/\r\n?|\n/);};
CodeMirror.splitLines = splitLines;
var hasSelection = window.getSelection ? function(te) {
try { return te.selectionStart != te.selectionEnd; }
catch(e) { return false; }
} : function(te) {
try {var range = te.ownerDocument.selection.createRange();}
catch(e) {}
if (!range || range.parentElement() != te) return false;
return range.compareEndPoints("StartToEnd", range) != 0;
};
CodeMirror.defineMode("null", function() {
return {token: function(stream) {stream.skipToEnd();}};
});
CodeMirror.defineMIME("text/plain", "null");
var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
46: "Delete", 59: ";", 91: "Mod", 92: "Mod", 93: "Mod", 109: "-", 107: "=", 127: "Delete",
186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
221: "]", 222: "'", 63276: "PageUp", 63277: "PageDown", 63275: "End", 63273: "Home",
63234: "Left", 63232: "Up", 63235: "Right", 63233: "Down", 63302: "Insert", 63272: "Delete"};
CodeMirror.keyNames = keyNames;
(function() {
// Number keys
for (var i = 0; i < 10; i++) keyNames[i + 48] = String(i);
// Alphabetic keys
for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
// Function keys
for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
})();
CodeMirror.version = "2.35";
return CodeMirror;
})();
/**
* Tag-closer extension for CodeMirror.
*
* This extension adds a "closeTag" utility function that can be used with key bindings to
* insert a matching end tag after the ">" character of a start tag has been typed. It can
* also complete "</" if a matching start tag is found. It will correctly ignore signal
* characters for empty tags, comments, CDATA, etc.
*
* The function depends on internal parser state to identify tags. It is compatible with the
* following CodeMirror modes and will ignore all others:
* - htmlmixed
* - xml
*
* See demos/closetag.html for a usage example.
*
* @author Nathan Williams <nathan@nlwillia.net>
* Contributed under the same license terms as CodeMirror.
*/
(function() {
/** Option that allows tag closing behavior to be toggled. Default is true. */
CodeMirror.defaults['closeTagEnabled'] = true;
/** Array of tag names to add indentation after the start tag for. Default is the list of block-level html tags. */
CodeMirror.defaults['closeTagIndent'] = ['applet', 'blockquote', 'body', 'button', 'div', 'dl', 'fieldset', 'form', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'html', 'iframe', 'layer', 'legend', 'object', 'ol', 'p', 'select', 'table', 'ul'];
/** Array of tag names where an end tag is forbidden. */
CodeMirror.defaults['closeTagVoid'] = ['area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr'];
function innerState(cm, state) {
return CodeMirror.innerMode(cm.getMode(), state).state;
}
/**
* Call during key processing to close tags. Handles the key event if the tag is closed, otherwise throws CodeMirror.Pass.
* - cm: The editor instance.
* - ch: The character being processed.
* - indent: Optional. An array of tag names to indent when closing. Omit or pass true to use the default indentation tag list defined in the 'closeTagIndent' option.
* Pass false to disable indentation. Pass an array to override the default list of tag names.
* - vd: Optional. An array of tag names that should not be closed. Omit to use the default void (end tag forbidden) tag list defined in the 'closeTagVoid' option. Ignored in xml mode.
*/
CodeMirror.defineExtension("closeTag", function(cm, ch, indent, vd) {
if (!cm.getOption('closeTagEnabled')) {
throw CodeMirror.Pass;
}
/*
* Relevant structure of token:
*
* htmlmixed
* className
* state
* htmlState
* type
* tagName
* context
* tagName
* mode
*
* xml
* className
* state
* tagName
* type
*/
var pos = cm.getCursor();
var tok = cm.getTokenAt(pos);
var state = innerState(cm, tok.state);
if (state) {
if (ch == '>') {
var type = state.type;
if (tok.className == 'tag' && type == 'closeTag') {
throw CodeMirror.Pass; // Don't process the '>' at the end of an end-tag.
}
cm.replaceSelection('>'); // Mode state won't update until we finish the tag.
pos = {line: pos.line, ch: pos.ch + 1};
cm.setCursor(pos);
tok = cm.getTokenAt(cm.getCursor());
state = innerState(cm, tok.state);
if (!state) throw CodeMirror.Pass;
var type = state.type;
if (tok.className == 'tag' && type != 'selfcloseTag') {
var tagName = state.tagName;
if (tagName.length > 0 && shouldClose(cm, vd, tagName)) {
insertEndTag(cm, indent, pos, tagName);
}
return;
}
// Undo the '>' insert and allow cm to handle the key instead.
cm.setSelection({line: pos.line, ch: pos.ch - 1}, pos);
cm.replaceSelection("");
} else if (ch == '/') {
if (tok.className == 'tag' && tok.string == '<') {
var ctx = state.context, tagName = ctx ? ctx.tagName : '';
if (tagName.length > 0) {
completeEndTag(cm, pos, tagName);
return;
}
}
}
}
throw CodeMirror.Pass; // Bubble if not handled
});
function insertEndTag(cm, indent, pos, tagName) {
if (shouldIndent(cm, indent, tagName)) {
cm.replaceSelection('\n\n</' + tagName + '>', 'end');
cm.indentLine(pos.line + 1);
cm.indentLine(pos.line + 2);
cm.setCursor({line: pos.line + 1, ch: cm.getLine(pos.line + 1).length});
} else {
cm.replaceSelection('</' + tagName + '>');
cm.setCursor(pos);
}
}
function shouldIndent(cm, indent, tagName) {
if (typeof indent == 'undefined' || indent == null || indent == true) {
indent = cm.getOption('closeTagIndent');
}
if (!indent) {
indent = [];
}
return indexOf(indent, tagName.toLowerCase()) != -1;
}
function shouldClose(cm, vd, tagName) {
if (cm.getOption('mode') == 'xml') {
return true; // always close xml tags
}
if (typeof vd == 'undefined' || vd == null) {
vd = cm.getOption('closeTagVoid');
}
if (!vd) {
vd = [];
}
return indexOf(vd, tagName.toLowerCase()) == -1;
}
// C&P from codemirror.js...would be nice if this were visible to utilities.
function indexOf(collection, elt) {
if (collection.indexOf) return collection.indexOf(elt);
for (var i = 0, e = collection.length; i < e; ++i)
if (collection[i] == elt) return i;
return -1;
}
function completeEndTag(cm, pos, tagName) {
cm.replaceSelection('/' + tagName + '>');
cm.setCursor({line: pos.line, ch: pos.ch + tagName.length + 2 });
}
})();
.CodeMirror-dialog {
position: relative;
}
.CodeMirror-dialog > div {
position: absolute;
top: 0; left: 0; right: 0;
background: white;
border-bottom: 1px solid #eee;
z-index: 15;
padding: .1em .8em;
overflow: hidden;
color: #333;
}
.CodeMirror-dialog input {
border: none;
outline: none;
background: transparent;
width: 20em;
color: inherit;
font-family: monospace;
}
.CodeMirror-dialog button {
font-size: 70%;
}
// Open simple dialogs on top of an editor. Relies on dialog.css.
(function() {
function dialogDiv(cm, template) {
var wrap = cm.getWrapperElement();
var dialog = wrap.insertBefore(document.createElement("div"), wrap.firstChild);
dialog.className = "CodeMirror-dialog";
dialog.innerHTML = '<div>' + template + '</div>';
return dialog;
}
CodeMirror.defineExtension("openDialog", function(template, callback) {
var dialog = dialogDiv(this, template);
var closed = false, me = this;
function close() {
if (closed) return;
closed = true;
dialog.parentNode.removeChild(dialog);
}
var inp = dialog.getElementsByTagName("input")[0], button;
if (inp) {
CodeMirror.connect(inp, "keydown", function(e) {
if (e.keyCode == 13 || e.keyCode == 27) {
CodeMirror.e_stop(e);
close();
me.focus();
if (e.keyCode == 13) callback(inp.value);
}
});
inp.focus();
CodeMirror.connect(inp, "blur", close);
} else if (button = dialog.getElementsByTagName("button")[0]) {
CodeMirror.connect(button, "click", function() {
close();
me.focus();
});
button.focus();
CodeMirror.connect(button, "blur", close);
}
return close;
});
CodeMirror.defineExtension("openConfirm", function(template, callbacks) {
var dialog = dialogDiv(this, template);
var buttons = dialog.getElementsByTagName("button");
var closed = false, me = this, blurring = 1;
function close() {
if (closed) return;
closed = true;
dialog.parentNode.removeChild(dialog);
me.focus();
}
buttons[0].focus();
for (var i = 0; i < buttons.length; ++i) {
var b = buttons[i];
(function(callback) {
CodeMirror.connect(b, "click", function(e) {
CodeMirror.e_preventDefault(e);
close();
if (callback) callback(me);
});
})(callbacks[i]);
CodeMirror.connect(b, "blur", function() {
--blurring;
setTimeout(function() { if (blurring <= 0) close(); }, 200);
});
CodeMirror.connect(b, "focus", function() { ++blurring; });
}
});
})();
// the tagRangeFinder function is
// Copyright (C) 2011 by Daniel Glazman <daniel@glazman.org>
// released under the MIT license (../../LICENSE) like the rest of CodeMirror
CodeMirror.tagRangeFinder = function(cm, line, hideEnd) {
var nameStartChar = "A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
var nameChar = nameStartChar + "\-\:\.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
var xmlNAMERegExp = new RegExp("^[" + nameStartChar + "][" + nameChar + "]*");
var lineText = cm.getLine(line);
var found = false;
var tag = null;
var pos = 0;
while (!found) {
pos = lineText.indexOf("<", pos);
if (-1 == pos) // no tag on line
return;
if (pos + 1 < lineText.length && lineText[pos + 1] == "/") { // closing tag
pos++;
continue;
}
// ok we weem to have a start tag
if (!lineText.substr(pos + 1).match(xmlNAMERegExp)) { // not a tag name...
pos++;
continue;
}
var gtPos = lineText.indexOf(">", pos + 1);
if (-1 == gtPos) { // end of start tag not in line
var l = line + 1;
var foundGt = false;
var lastLine = cm.lineCount();
while (l < lastLine && !foundGt) {
var lt = cm.getLine(l);
var gt = lt.indexOf(">");
if (-1 != gt) { // found a >
foundGt = true;
var slash = lt.lastIndexOf("/", gt);
if (-1 != slash && slash < gt) {
var str = lineText.substr(slash, gt - slash + 1);
if (!str.match( /\/\s*\>/ )) { // yep, that's the end of empty tag
if (hideEnd === true) l++;
return l;
}
}
}
l++;
}
found = true;
}
else {
var slashPos = lineText.lastIndexOf("/", gtPos);
if (-1 == slashPos) { // cannot be empty tag
found = true;
// don't continue
}
else { // empty tag?
// check if really empty tag
var str = lineText.substr(slashPos, gtPos - slashPos + 1);
if (!str.match( /\/\s*\>/ )) { // finally not empty
found = true;
// don't continue
}
}
}
if (found) {
var subLine = lineText.substr(pos + 1);
tag = subLine.match(xmlNAMERegExp);
if (tag) {
// we have an element name, wooohooo !
tag = tag[0];
// do we have the close tag on same line ???
if (-1 != lineText.indexOf("</" + tag + ">", pos)) // yep
{
found = false;
}
// we don't, so we have a candidate...
}
else
found = false;
}
if (!found)
pos++;
}
if (found) {
var startTag = "(\\<\\/" + tag + "\\>)|(\\<" + tag + "\\>)|(\\<" + tag + "\\s)|(\\<" + tag + "$)";
var startTagRegExp = new RegExp(startTag, "g");
var endTag = "</" + tag + ">";
var depth = 1;
var l = line + 1;
var lastLine = cm.lineCount();
while (l < lastLine) {
lineText = cm.getLine(l);
var match = lineText.match(startTagRegExp);
if (match) {
for (var i = 0; i < match.length; i++) {
if (match[i] == endTag)
depth--;
else
depth++;
if (!depth) {
if (hideEnd === true) l++;
return l;
}
}
}
l++;
}
return;
}
};
CodeMirror.braceRangeFinder = function(cm, line, hideEnd) {
var lineText = cm.getLine(line), at = lineText.length, startChar, tokenType;
for (;;) {
var found = lineText.lastIndexOf("{", at);
if (found < 0) break;
tokenType = cm.getTokenAt({line: line, ch: found}).className;
if (!/^(comment|string)/.test(tokenType)) { startChar = found; break; }
at = found - 1;
}
if (startChar == null || lineText.lastIndexOf("}") > startChar) return;
var count = 1, lastLine = cm.lineCount(), end;
outer: for (var i = line + 1; i < lastLine; ++i) {
var text = cm.getLine(i), pos = 0;
for (;;) {
var nextOpen = text.indexOf("{", pos), nextClose = text.indexOf("}", pos);
if (nextOpen < 0) nextOpen = text.length;
if (nextClose < 0) nextClose = text.length;
pos = Math.min(nextOpen, nextClose);
if (pos == text.length) break;
if (cm.getTokenAt({line: i, ch: pos + 1}).className == tokenType) {
if (pos == nextOpen) ++count;
else if (!--count) { end = i; break outer; }
}
++pos;
}
}
if (end == null || end == line + 1) return;
if (hideEnd === true) end++;
return end;
};
CodeMirror.indentRangeFinder = function(cm, line) {
var tabSize = cm.getOption("tabSize");
var myIndent = cm.getLineHandle(line).indentation(tabSize), last;
for (var i = line + 1, end = cm.lineCount(); i < end; ++i) {
var handle = cm.getLineHandle(i);
if (!/^\s*$/.test(handle.text)) {
if (handle.indentation(tabSize) <= myIndent) break;
last = i;
}
}
if (!last) return null;
return last + 1;
};
CodeMirror.newFoldFunction = function(rangeFinder, markText, hideEnd) {
var folded = [];
if (markText == null) markText = '<div style="position: absolute; left: 2px; color:#600">&#x25bc;</div>%N%';
function isFolded(cm, n) {
for (var i = 0; i < folded.length; ++i) {
var start = cm.lineInfo(folded[i].start);
if (!start) folded.splice(i--, 1);
else if (start.line == n) return {pos: i, region: folded[i]};
}
}
function expand(cm, region) {
cm.clearMarker(region.start);
for (var i = 0; i < region.hidden.length; ++i)
cm.showLine(region.hidden[i]);
}
return function(cm, line) {
cm.operation(function() {
var known = isFolded(cm, line);
if (known) {
folded.splice(known.pos, 1);
expand(cm, known.region);
} else {
var end = rangeFinder(cm, line, hideEnd);
if (end == null) return;
var hidden = [];
for (var i = line + 1; i < end; ++i) {
var handle = cm.hideLine(i);
if (handle) hidden.push(handle);
}
var first = cm.setMarker(line, markText);
var region = {start: first, hidden: hidden};
cm.onDeleteLine(first, function() { expand(cm, region); });
folded.push(region);
}
});
};
};
// ============== Formatting extensions ============================
(function() {
// Define extensions for a few modes
CodeMirror.extendMode("css", {
commentStart: "/*",
commentEnd: "*/",
wordWrapChars: [";", "\\{", "\\}"],
autoFormatLineBreaks: function (text) {
return text.replace(new RegExp("(;|\\{|\\})([^\r\n])", "g"), "$1\n$2");
}
});
function jsNonBreakableBlocks(text) {
var nonBreakableRegexes = [/for\s*?\((.*?)\)/,
/\"(.*?)(\"|$)/,
/\'(.*?)(\'|$)/,
/\/\*(.*?)(\*\/|$)/,
/\/\/.*/];
var nonBreakableBlocks = [];
for (var i = 0; i < nonBreakableRegexes.length; i++) {
var curPos = 0;
while (curPos < text.length) {
var m = text.substr(curPos).match(nonBreakableRegexes[i]);
if (m != null) {
nonBreakableBlocks.push({
start: curPos + m.index,
end: curPos + m.index + m[0].length
});
curPos += m.index + Math.max(1, m[0].length);
}
else { // No more matches
break;
}
}
}
nonBreakableBlocks.sort(function (a, b) {
return a.start - b.start;
});
return nonBreakableBlocks;
}
CodeMirror.extendMode("javascript", {
commentStart: "/*",
commentEnd: "*/",
wordWrapChars: [";", "\\{", "\\}"],
autoFormatLineBreaks: function (text) {
var curPos = 0;
var reLinesSplitter = /(;|\{|\})([^\r\n;])/g;
var nonBreakableBlocks = jsNonBreakableBlocks(text);
if (nonBreakableBlocks != null) {
var res = "";
for (var i = 0; i < nonBreakableBlocks.length; i++) {
if (nonBreakableBlocks[i].start > curPos) { // Break lines till the block
res += text.substring(curPos, nonBreakableBlocks[i].start).replace(reLinesSplitter, "$1\n$2");
curPos = nonBreakableBlocks[i].start;
}
if (nonBreakableBlocks[i].start <= curPos
&& nonBreakableBlocks[i].end >= curPos) { // Skip non-breakable block
res += text.substring(curPos, nonBreakableBlocks[i].end);
curPos = nonBreakableBlocks[i].end;
}
}
if (curPos < text.length)
res += text.substr(curPos).replace(reLinesSplitter, "$1\n$2");
return res;
} else {
return text.replace(reLinesSplitter, "$1\n$2");
}
}
});
CodeMirror.extendMode("xml", {
commentStart: "<!--",
commentEnd: "-->",
wordWrapChars: [">"],
autoFormatLineBreaks: function (text) {
var lines = text.split("\n");
var reProcessedPortion = new RegExp("(^\\s*?<|^[^<]*?)(.+)(>\\s*?$|[^>]*?$)");
var reOpenBrackets = new RegExp("<", "g");
var reCloseBrackets = new RegExp("(>)([^\r\n])", "g");
for (var i = 0; i < lines.length; i++) {
var mToProcess = lines[i].match(reProcessedPortion);
if (mToProcess != null && mToProcess.length > 3) { // The line starts with whitespaces and ends with whitespaces
lines[i] = mToProcess[1]
+ mToProcess[2].replace(reOpenBrackets, "\n$&").replace(reCloseBrackets, "$1\n$2")
+ mToProcess[3];
continue;
}
}
return lines.join("\n");
}
});
function localModeAt(cm, pos) {
return CodeMirror.innerMode(cm.getMode(), cm.getTokenAt(pos).state).mode;
}
function enumerateModesBetween(cm, line, start, end) {
var outer = cm.getMode(), text = cm.getLine(line);
if (end == null) end = text.length;
if (!outer.innerMode) return [{from: start, to: end, mode: outer}];
var state = cm.getTokenAt({line: line, ch: start}).state;
var mode = CodeMirror.innerMode(outer, state).mode;
var found = [], stream = new CodeMirror.StringStream(text);
stream.pos = stream.start = start;
for (;;) {
outer.token(stream, state);
var curMode = CodeMirror.innerMode(outer, state).mode;
if (curMode != mode) {
var cut = stream.start;
// Crappy heuristic to deal with the fact that a change in
// mode can occur both at the end and the start of a token,
// and we don't know which it was.
if (mode.name == "xml" && text.charAt(stream.pos - 1) == ">") cut = stream.pos;
found.push({from: start, to: cut, mode: mode});
start = cut;
mode = curMode;
}
if (stream.pos >= end) break;
stream.start = stream.pos;
}
if (start < end) found.push({from: start, to: end, mode: mode});
return found;
}
// Comment/uncomment the specified range
CodeMirror.defineExtension("commentRange", function (isComment, from, to) {
var curMode = localModeAt(this, from), cm = this;
this.operation(function() {
if (isComment) { // Comment range
cm.replaceRange(curMode.commentEnd, to);
cm.replaceRange(curMode.commentStart, from);
if (from.line == to.line && from.ch == to.ch) // An empty comment inserted - put cursor inside
cm.setCursor(from.line, from.ch + curMode.commentStart.length);
} else { // Uncomment range
var selText = cm.getRange(from, to);
var startIndex = selText.indexOf(curMode.commentStart);
var endIndex = selText.lastIndexOf(curMode.commentEnd);
if (startIndex > -1 && endIndex > -1 && endIndex > startIndex) {
// Take string till comment start
selText = selText.substr(0, startIndex)
// From comment start till comment end
+ selText.substring(startIndex + curMode.commentStart.length, endIndex)
// From comment end till string end
+ selText.substr(endIndex + curMode.commentEnd.length);
}
cm.replaceRange(selText, from, to);
}
});
});
// Applies automatic mode-aware indentation to the specified range
CodeMirror.defineExtension("autoIndentRange", function (from, to) {
var cmInstance = this;
this.operation(function () {
for (var i = from.line; i <= to.line; i++) {
cmInstance.indentLine(i, "smart");
}
});
});
// Applies automatic formatting to the specified range
CodeMirror.defineExtension("autoFormatRange", function (from, to) {
var cm = this;
cm.operation(function () {
for (var cur = from.line, end = to.line; cur <= end; ++cur) {
var f = {line: cur, ch: cur == from.line ? from.ch : 0};
var t = {line: cur, ch: cur == end ? to.ch : null};
var modes = enumerateModesBetween(cm, cur, f.ch, t.ch), mangled = "";
var text = cm.getRange(f, t);
for (var i = 0; i < modes.length; ++i) {
var part = modes.length > 1 ? text.slice(modes[i].from, modes[i].to) : text;
if (mangled) mangled += "\n";
if (modes[i].mode.autoFormatLineBreaks) {
mangled += modes[i].mode.autoFormatLineBreaks(part);
} else mangled += text;
}
if (mangled != text) {
for (var count = 0, pos = mangled.indexOf("\n"); pos != -1; pos = mangled.indexOf("\n", pos + 1), ++count) {}
cm.replaceRange(mangled, f, t);
cur += count;
end += count;
}
}
for (var cur = from.line + 1; cur <= end; ++cur)
cm.indentLine(cur, "smart");
cm.setSelection(from, cm.getCursor(false));
});
});
})();
(function () {
function forEach(arr, f) {
for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]);
}
function arrayContains(arr, item) {
if (!Array.prototype.indexOf) {
var i = arr.length;
while (i--) {
if (arr[i] === item) {
return true;
}
}
return false;
}
return arr.indexOf(item) != -1;
}
function scriptHint(editor, keywords, getToken) {
// Find the token at the cursor
var cur = editor.getCursor(), token = getToken(editor, cur), tprop = token;
// If it's not a 'word-style' token, ignore the token.
if (!/^[\w$_]*$/.test(token.string)) {
token = tprop = {start: cur.ch, end: cur.ch, string: "", state: token.state,
className: token.string == "." ? "property" : null};
}
// If it is a property, find out what it is a property of.
while (tprop.className == "property") {
tprop = getToken(editor, {line: cur.line, ch: tprop.start});
if (tprop.string != ".") return;
tprop = getToken(editor, {line: cur.line, ch: tprop.start});
if (tprop.string == ')') {
var level = 1;
do {
tprop = getToken(editor, {line: cur.line, ch: tprop.start});
switch (tprop.string) {
case ')': level++; break;
case '(': level--; break;
default: break;
}
} while (level > 0);
tprop = getToken(editor, {line: cur.line, ch: tprop.start});
if (tprop.className == 'variable')
tprop.className = 'function';
else return; // no clue
}
if (!context) var context = [];
context.push(tprop);
}
return {list: getCompletions(token, context, keywords),
from: {line: cur.line, ch: token.start},
to: {line: cur.line, ch: token.end}};
}
CodeMirror.javascriptHint = function(editor) {
return scriptHint(editor, javascriptKeywords,
function (e, cur) {return e.getTokenAt(cur);});
};
function getCoffeeScriptToken(editor, cur) {
// This getToken, it is for coffeescript, imitates the behavior of
// getTokenAt method in javascript.js, that is, returning "property"
// type and treat "." as indepenent token.
var token = editor.getTokenAt(cur);
if (cur.ch == token.start + 1 && token.string.charAt(0) == '.') {
token.end = token.start;
token.string = '.';
token.className = "property";
}
else if (/^\.[\w$_]*$/.test(token.string)) {
token.className = "property";
token.start++;
token.string = token.string.replace(/\./, '');
}
return token;
}
CodeMirror.coffeescriptHint = function(editor) {
return scriptHint(editor, coffeescriptKeywords, getCoffeeScriptToken);
};
var stringProps = ("charAt charCodeAt indexOf lastIndexOf substring substr slice trim trimLeft trimRight " +
"toUpperCase toLowerCase split concat match replace search").split(" ");
var arrayProps = ("length concat join splice push pop shift unshift slice reverse sort indexOf " +
"lastIndexOf every some filter forEach map reduce reduceRight ").split(" ");
var funcProps = "prototype apply call bind".split(" ");
var javascriptKeywords = ("break case catch continue debugger default delete do else false finally for function " +
"if in instanceof new null return switch throw true try typeof var void while with").split(" ");
var coffeescriptKeywords = ("and break catch class continue delete do else extends false finally for " +
"if in instanceof isnt new no not null of off on or return switch then throw true try typeof until void while with yes").split(" ");
function getCompletions(token, context, keywords) {
var found = [], start = token.string;
function maybeAdd(str) {
if (str.indexOf(start) == 0 && !arrayContains(found, str)) found.push(str);
}
function gatherCompletions(obj) {
if (typeof obj == "string") forEach(stringProps, maybeAdd);
else if (obj instanceof Array) forEach(arrayProps, maybeAdd);
else if (obj instanceof Function) forEach(funcProps, maybeAdd);
for (var name in obj) maybeAdd(name);
}
if (context) {
// If this is a property, see if it belongs to some object we can
// find in the current environment.
var obj = context.pop(), base;
if (obj.className == "variable")
base = window[obj.string];
else if (obj.className == "string")
base = "";
else if (obj.className == "atom")
base = 1;
else if (obj.className == "function") {
if (window.jQuery != null && (obj.string == '$' || obj.string == 'jQuery') &&
(typeof window.jQuery == 'function'))
base = window.jQuery();
else if (window._ != null && (obj.string == '_') && (typeof window._ == 'function'))
base = window._();
}
while (base != null && context.length)
base = base[context.pop().string];
if (base != null) gatherCompletions(base);
}
else {
// If not, just look in the window object and any local scope
// (reading into JS mode internals to get at the local variables)
for (var v = token.state.localVars; v; v = v.next) maybeAdd(v.name);
gatherCompletions(window);
forEach(keywords, maybeAdd);
}
return found;
}
})();
(function() {
if (!CodeMirror.modeURL) CodeMirror.modeURL = "../mode/%N/%N.js";
var loading = {};
function splitCallback(cont, n) {
var countDown = n;
return function() { if (--countDown == 0) cont(); };
}
function ensureDeps(mode, cont) {
var deps = CodeMirror.modes[mode].dependencies;
if (!deps) return cont();
var missing = [];
for (var i = 0; i < deps.length; ++i) {
if (!CodeMirror.modes.hasOwnProperty(deps[i]))
missing.push(deps[i]);
}
if (!missing.length) return cont();
var split = splitCallback(cont, missing.length);
for (var i = 0; i < missing.length; ++i)
CodeMirror.requireMode(missing[i], split);
}
CodeMirror.requireMode = function(mode, cont) {
if (typeof mode != "string") mode = mode.name;
if (CodeMirror.modes.hasOwnProperty(mode)) return ensureDeps(mode, cont);
if (loading.hasOwnProperty(mode)) return loading[mode].push(cont);
var script = document.createElement("script");
script.src = CodeMirror.modeURL.replace(/%N/g, mode);
var others = document.getElementsByTagName("script")[0];
others.parentNode.insertBefore(script, others);
var list = loading[mode] = [cont];
var count = 0, poll = setInterval(function() {
if (++count > 100) return clearInterval(poll);
if (CodeMirror.modes.hasOwnProperty(mode)) {
clearInterval(poll);
loading[mode] = null;
ensureDeps(mode, function() {
for (var i = 0; i < list.length; ++i) list[i]();
});
}
}, 200);
};
CodeMirror.autoLoadMode = function(instance, mode) {
if (!CodeMirror.modes.hasOwnProperty(mode))
CodeMirror.requireMode(mode, function() {
instance.setOption("mode", instance.getOption("mode"));
});
};
}());
// Define match-highlighter commands. Depends on searchcursor.js
// Use by attaching the following function call to the onCursorActivity event:
//myCodeMirror.matchHighlight(minChars);
// And including a special span.CodeMirror-matchhighlight css class (also optionally a separate one for .CodeMirror-focused -- see demo matchhighlighter.html)
(function() {
var DEFAULT_MIN_CHARS = 2;
function MatchHighlightState() {
this.marked = [];
}
function getMatchHighlightState(cm) {
return cm._matchHighlightState || (cm._matchHighlightState = new MatchHighlightState());
}
function clearMarks(cm) {
var state = getMatchHighlightState(cm);
for (var i = 0; i < state.marked.length; ++i)
state.marked[i].clear();
state.marked = [];
}
function markDocument(cm, className, minChars) {
clearMarks(cm);
minChars = (typeof minChars !== 'undefined' ? minChars : DEFAULT_MIN_CHARS);
if (cm.somethingSelected() && cm.getSelection().replace(/^\s+|\s+$/g, "").length >= minChars) {
var state = getMatchHighlightState(cm);
var query = cm.getSelection();
cm.operation(function() {
if (cm.lineCount() < 2000) { // This is too expensive on big documents.
for (var cursor = cm.getSearchCursor(query); cursor.findNext();) {
//Only apply matchhighlight to the matches other than the one actually selected
if (!(cursor.from().line === cm.getCursor(true).line && cursor.from().ch === cm.getCursor(true).ch))
state.marked.push(cm.markText(cursor.from(), cursor.to(), className));
}
}
});
}
}
CodeMirror.defineExtension("matchHighlight", function(className, minChars) {
markDocument(this, className, minChars);
});
})();
CodeMirror.multiplexingMode = function(outer /*, others */) {
// Others should be {open, close, mode [, delimStyle]} objects
var others = Array.prototype.slice.call(arguments, 1);
var n_others = others.length;
function indexOf(string, pattern, from) {
if (typeof pattern == "string") return string.indexOf(pattern, from);
var m = pattern.exec(from ? string.slice(from) : string);
return m ? m.index + from : -1;
}
return {
startState: function() {
return {
outer: CodeMirror.startState(outer),
innerActive: null,
inner: null
};
},
copyState: function(state) {
return {
outer: CodeMirror.copyState(outer, state.outer),
innerActive: state.innerActive,
inner: state.innerActive && CodeMirror.copyState(state.innerActive.mode, state.inner)
};
},
token: function(stream, state) {
if (!state.innerActive) {
var cutOff = Infinity, oldContent = stream.string;
for (var i = 0; i < n_others; ++i) {
var other = others[i];
var found = indexOf(oldContent, other.open, stream.pos);
if (found == stream.pos) {
stream.match(other.open);
state.innerActive = other;
state.inner = CodeMirror.startState(other.mode, outer.indent ? outer.indent(state.outer, "") : 0);
return other.delimStyle;
} else if (found != -1 && found < cutOff) {
cutOff = found;
}
}
if (cutOff != Infinity) stream.string = oldContent.slice(0, cutOff);
var outerToken = outer.token(stream, state.outer);
if (cutOff != Infinity) stream.string = oldContent;
return outerToken;
} else {
var curInner = state.innerActive, oldContent = stream.string;
var found = indexOf(oldContent, curInner.close, stream.pos);
if (found == stream.pos) {
stream.match(curInner.close);
state.innerActive = state.inner = null;
return curInner.delimStyle;
}
if (found > -1) stream.string = oldContent.slice(0, found);
var innerToken = curInner.mode.token(stream, state.inner);
if (found > -1) stream.string = oldContent;
var cur = stream.current(), found = cur.indexOf(curInner.close);
if (found > -1) stream.backUp(cur.length - found);
return innerToken;
}
},
indent: function(state, textAfter) {
var mode = state.innerActive ? state.innerActive.mode : outer;
if (!mode.indent) return CodeMirror.Pass;
return mode.indent(state.innerActive ? state.inner : state.outer, textAfter);
},
electricChars: outer.electricChars,
innerMode: function(state) {
return state.inner ? {state: state.inner, mode: state.innerActive.mode} : {state: state.outer, mode: outer};
}
};
};
// Utility function that allows modes to be combined. The mode given
// as the base argument takes care of most of the normal mode
// functionality, but a second (typically simple) mode is used, which
// can override the style of text. Both modes get to parse all of the
// text, but when both assign a non-null style to a piece of code, the
// overlay wins, unless the combine argument was true, in which case
// the styles are combined.
// overlayParser is the old, deprecated name
CodeMirror.overlayMode = CodeMirror.overlayParser = function(base, overlay, combine) {
return {
startState: function() {
return {
base: CodeMirror.startState(base),
overlay: CodeMirror.startState(overlay),
basePos: 0, baseCur: null,
overlayPos: 0, overlayCur: null
};
},
copyState: function(state) {
return {
base: CodeMirror.copyState(base, state.base),
overlay: CodeMirror.copyState(overlay, state.overlay),
basePos: state.basePos, baseCur: null,
overlayPos: state.overlayPos, overlayCur: null
};
},
token: function(stream, state) {
if (stream.start == state.basePos) {
state.baseCur = base.token(stream, state.base);
state.basePos = stream.pos;
}
if (stream.start == state.overlayPos) {
stream.pos = stream.start;
state.overlayCur = overlay.token(stream, state.overlay);
state.overlayPos = stream.pos;
}
stream.pos = Math.min(state.basePos, state.overlayPos);
if (stream.eol()) state.basePos = state.overlayPos = 0;
if (state.overlayCur == null) return state.baseCur;
if (state.baseCur != null && combine) return state.baseCur + " " + state.overlayCur;
else return state.overlayCur;
},
indent: base.indent && function(state, textAfter) {
return base.indent(state.base, textAfter);
},
electricChars: base.electricChars,
innerMode: function(state) { return {state: state.base, mode: base}; },
blankLine: function(state) {
if (base.blankLine) base.blankLine(state.base);
if (overlay.blankLine) overlay.blankLine(state.overlay);
}
};
};
(function () {
function forEach(arr, f) {
for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]);
}
function arrayContains(arr, item) {
if (!Array.prototype.indexOf) {
var i = arr.length;
while (i--) {
if (arr[i] === item) {
return true;
}
}
return false;
}
return arr.indexOf(item) != -1;
}
function scriptHint(editor, keywords, getToken) {
// Find the token at the cursor
var cur = editor.getCursor(), token = getToken(editor, cur), tprop = token;
// If it's not a 'word-style' token, ignore the token.
if (!/^[\w$_]*$/.test(token.string)) {
token = tprop = {start: cur.ch, end: cur.ch, string: "", state: token.state,
className: token.string == ":" ? "pig-type" : null};
}
if (!context) var context = [];
context.push(tprop);
var completionList = getCompletions(token, context);
completionList = completionList.sort();
//prevent autocomplete for last word, instead show dropdown with one word
if(completionList.length == 1) {
completionList.push(" ");
}
return {list: completionList,
from: {line: cur.line, ch: token.start},
to: {line: cur.line, ch: token.end}};
}
CodeMirror.pigHint = function(editor) {
return scriptHint(editor, pigKeywordsU, function (e, cur) {return e.getTokenAt(cur);});
};
function toTitleCase(str) {
return str.replace(/(?:^|\s)\w/g, function(match) {
return match.toUpperCase();
});
}
var pigKeywords = "VOID IMPORT RETURNS DEFINE LOAD FILTER FOREACH ORDER CUBE DISTINCT COGROUP "
+ "JOIN CROSS UNION SPLIT INTO IF OTHERWISE ALL AS BY USING INNER OUTER ONSCHEMA PARALLEL "
+ "PARTITION GROUP AND OR NOT GENERATE FLATTEN ASC DESC IS STREAM THROUGH STORE MAPREDUCE "
+ "SHIP CACHE INPUT OUTPUT STDERROR STDIN STDOUT LIMIT SAMPLE LEFT RIGHT FULL EQ GT LT GTE LTE "
+ "NEQ MATCHES TRUE FALSE";
var pigKeywordsU = pigKeywords.split(" ");
var pigKeywordsL = pigKeywords.toLowerCase().split(" ");
var pigTypes = "BOOLEAN INT LONG FLOAT DOUBLE CHARARRAY BYTEARRAY BAG TUPLE MAP";
var pigTypesU = pigTypes.split(" ");
var pigTypesL = pigTypes.toLowerCase().split(" ");
var pigBuiltins = "ABS ACOS ARITY ASIN ATAN AVG BAGSIZE BINSTORAGE BLOOM BUILDBLOOM CBRT CEIL "
+ "CONCAT COR COS COSH COUNT COUNT_STAR COV CONSTANTSIZE CUBEDIMENSIONS DIFF DISTINCT DOUBLEABS "
+ "DOUBLEAVG DOUBLEBASE DOUBLEMAX DOUBLEMIN DOUBLEROUND DOUBLESUM EXP FLOOR FLOATABS FLOATAVG "
+ "FLOATMAX FLOATMIN FLOATROUND FLOATSUM GENERICINVOKER INDEXOF INTABS INTAVG INTMAX INTMIN "
+ "INTSUM INVOKEFORDOUBLE INVOKEFORFLOAT INVOKEFORINT INVOKEFORLONG INVOKEFORSTRING INVOKER "
+ "ISEMPTY JSONLOADER JSONMETADATA JSONSTORAGE LAST_INDEX_OF LCFIRST LOG LOG10 LOWER LONGABS "
+ "LONGAVG LONGMAX LONGMIN LONGSUM MAX MIN MAPSIZE MONITOREDUDF NONDETERMINISTIC OUTPUTSCHEMA "
+ "PIGSTORAGE PIGSTREAMING RANDOM REGEX_EXTRACT REGEX_EXTRACT_ALL REPLACE ROUND SIN SINH SIZE "
+ "SQRT STRSPLIT SUBSTRING SUM STRINGCONCAT STRINGMAX STRINGMIN STRINGSIZE TAN TANH TOBAG "
+ "TOKENIZE TOMAP TOP TOTUPLE TRIM TEXTLOADER TUPLESIZE UCFIRST UPPER UTF8STORAGECONVERTER";
var pigBuiltinsU = pigBuiltins.split(" ").join("() ").split(" ");
var pigBuiltinsL = pigBuiltins.toLowerCase().split(" ").join("() ").split(" ");
var pigBuiltinsC = ("BagSize BinStorage Bloom BuildBloom ConstantSize CubeDimensions DoubleAbs "
+ "DoubleAvg DoubleBase DoubleMax DoubleMin DoubleRound DoubleSum FloatAbs FloatAvg FloatMax "
+ "FloatMin FloatRound FloatSum GenericInvoker IntAbs IntAvg IntMax IntMin IntSum "
+ "InvokeForDouble InvokeForFloat InvokeForInt InvokeForLong InvokeForString Invoker "
+ "IsEmpty JsonLoader JsonMetadata JsonStorage LongAbs LongAvg LongMax LongMin LongSum MapSize "
+ "MonitoredUDF Nondeterministic OutputSchema PigStorage PigStreaming StringConcat StringMax "
+ "StringMin StringSize TextLoader TupleSize Utf8StorageConverter").split(" ").join("() ").split(" ");
function getCompletions(token, context) {
var found = [], start = token.string;
function maybeAdd(str) {
if (str.indexOf(start) == 0 && !arrayContains(found, str)) found.push(str);
}
function gatherCompletions(obj) {
if(obj == ":") {
forEach(pigTypesL, maybeAdd);
}
else {
forEach(pigBuiltinsU, maybeAdd);
forEach(pigBuiltinsL, maybeAdd);
forEach(pigBuiltinsC, maybeAdd);
forEach(pigTypesU, maybeAdd);
forEach(pigTypesL, maybeAdd);
forEach(pigKeywordsU, maybeAdd);
forEach(pigKeywordsL, maybeAdd);
}
}
if (context) {
// If this is a property, see if it belongs to some object we can
// find in the current environment.
var obj = context.pop(), base;
if (obj.className == "pig-word")
base = obj.string;
else if(obj.className == "pig-type")
base = ":" + obj.string;
while (base != null && context.length)
base = base[context.pop().string];
if (base != null) gatherCompletions(base);
}
return found;
}
})();
/* Just enough of CodeMirror to run runMode under node.js */
function splitLines(string){ return string.split(/\r?\n|\r/); };
function StringStream(string) {
this.pos = this.start = 0;
this.string = string;
}
StringStream.prototype = {
eol: function() {return this.pos >= this.string.length;},
sol: function() {return this.pos == 0;},
peek: function() {return this.string.charAt(this.pos) || null;},
next: function() {
if (this.pos < this.string.length)
return this.string.charAt(this.pos++);
},
eat: function(match) {
var ch = this.string.charAt(this.pos);
if (typeof match == "string") var ok = ch == match;
else var ok = ch && (match.test ? match.test(ch) : match(ch));
if (ok) {++this.pos; return ch;}
},
eatWhile: function(match) {
var start = this.pos;
while (this.eat(match)){}
return this.pos > start;
},
eatSpace: function() {
var start = this.pos;
while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
return this.pos > start;
},
skipToEnd: function() {this.pos = this.string.length;},
skipTo: function(ch) {
var found = this.string.indexOf(ch, this.pos);
if (found > -1) {this.pos = found; return true;}
},
backUp: function(n) {this.pos -= n;},
column: function() {return this.start;},
indentation: function() {return 0;},
match: function(pattern, consume, caseInsensitive) {
if (typeof pattern == "string") {
function cased(str) {return caseInsensitive ? str.toLowerCase() : str;}
if (cased(this.string).indexOf(cased(pattern), this.pos) == this.pos) {
if (consume !== false) this.pos += pattern.length;
return true;
}
}
else {
var match = this.string.slice(this.pos).match(pattern);
if (match && consume !== false) this.pos += match[0].length;
return match;
}
},
current: function(){return this.string.slice(this.start, this.pos);}
};
exports.StringStream = StringStream;
exports.startState = function(mode, a1, a2) {
return mode.startState ? mode.startState(a1, a2) : true;
};
var modes = exports.modes = {}, mimeModes = exports.mimeModes = {};
exports.defineMode = function(name, mode) { modes[name] = mode; };
exports.defineMIME = function(mime, spec) { mimeModes[mime] = spec; };
exports.getMode = function(options, spec) {
if (typeof spec == "string" && mimeModes.hasOwnProperty(spec))
spec = mimeModes[spec];
if (typeof spec == "string")
var mname = spec, config = {};
else if (spec != null)
var mname = spec.name, config = spec;
var mfactory = modes[mname];
if (!mfactory) throw new Error("Unknown mode: " + spec);
return mfactory(options, config || {});
};
exports.runMode = function(string, modespec, callback) {
var mode = exports.getMode({indentUnit: 2}, modespec);
var lines = splitLines(string), state = exports.startState(mode);
for (var i = 0, e = lines.length; i < e; ++i) {
if (i) callback("\n");
var stream = new exports.StringStream(lines[i]);
while (!stream.eol()) {
var style = mode.token(stream, state);
callback(stream.current(), style, i, stream.start);
stream.start = stream.pos;
}
}
};
CodeMirror.runMode = function(string, modespec, callback, options) {
function esc(str) {
return str.replace(/[<&]/g, function(ch) { return ch == "<" ? "&lt;" : "&amp;"; });
}
var mode = CodeMirror.getMode(CodeMirror.defaults, modespec);
var isNode = callback.nodeType == 1;
var tabSize = (options && options.tabSize) || CodeMirror.defaults.tabSize;
if (isNode) {
var node = callback, accum = [], col = 0;
callback = function(text, style) {
if (text == "\n") {
accum.push("<br>");
col = 0;
return;
}
var escaped = "";
// HTML-escape and replace tabs
for (var pos = 0;;) {
var idx = text.indexOf("\t", pos);
if (idx == -1) {
escaped += esc(text.slice(pos));
col += text.length - pos;
break;
} else {
col += idx - pos;
escaped += esc(text.slice(pos, idx));
var size = tabSize - col % tabSize;
col += size;
for (var i = 0; i < size; ++i) escaped += " ";
pos = idx + 1;
}
}
if (style)
accum.push("<span class=\"cm-" + esc(style) + "\">" + escaped + "</span>");
else
accum.push(escaped);
};
}
var lines = CodeMirror.splitLines(string), state = CodeMirror.startState(mode);
for (var i = 0, e = lines.length; i < e; ++i) {
if (i) callback("\n");
var stream = new CodeMirror.StringStream(lines[i]);
while (!stream.eol()) {
var style = mode.token(stream, state);
callback(stream.current(), style, i, stream.start);
stream.start = stream.pos;
}
}
if (isNode)
node.innerHTML = accum.join("");
};
// Define search commands. Depends on dialog.js or another
// implementation of the openDialog method.
// Replace works a little oddly -- it will do the replace on the next
// Ctrl-G (or whatever is bound to findNext) press. You prevent a
// replace by making sure the match is no longer selected when hitting
// Ctrl-G.
(function() {
function SearchState() {
this.posFrom = this.posTo = this.query = null;
this.marked = [];
}
function getSearchState(cm) {
return cm._searchState || (cm._searchState = new SearchState());
}
function getSearchCursor(cm, query, pos) {
// Heuristic: if the query string is all lowercase, do a case insensitive search.
return cm.getSearchCursor(query, pos, typeof query == "string" && query == query.toLowerCase());
}
function dialog(cm, text, shortText, f) {
if (cm.openDialog) cm.openDialog(text, f);
else f(prompt(shortText, ""));
}
function confirmDialog(cm, text, shortText, fs) {
if (cm.openConfirm) cm.openConfirm(text, fs);
else if (confirm(shortText)) fs[0]();
}
function parseQuery(query) {
var isRE = query.match(/^\/(.*)\/([a-z]*)$/);
return isRE ? new RegExp(isRE[1], isRE[2].indexOf("i") == -1 ? "" : "i") : query;
}
var queryDialog =
'Search: <input type="text" style="width: 10em"/> <span style="color: #888">(Use /re/ syntax for regexp search)</span>';
function doSearch(cm, rev) {
var state = getSearchState(cm);
if (state.query) return findNext(cm, rev);
dialog(cm, queryDialog, "Search for:", function(query) {
cm.operation(function() {
if (!query || state.query) return;
state.query = parseQuery(query);
if (cm.lineCount() < 2000) { // This is too expensive on big documents.
for (var cursor = getSearchCursor(cm, state.query); cursor.findNext();)
state.marked.push(cm.markText(cursor.from(), cursor.to(), "CodeMirror-searching"));
}
state.posFrom = state.posTo = cm.getCursor();
findNext(cm, rev);
});
});
}
function findNext(cm, rev) {cm.operation(function() {
var state = getSearchState(cm);
var cursor = getSearchCursor(cm, state.query, rev ? state.posFrom : state.posTo);
if (!cursor.find(rev)) {
cursor = getSearchCursor(cm, state.query, rev ? {line: cm.lineCount() - 1} : {line: 0, ch: 0});
if (!cursor.find(rev)) return;
}
cm.setSelection(cursor.from(), cursor.to());
state.posFrom = cursor.from(); state.posTo = cursor.to();
});}
function clearSearch(cm) {cm.operation(function() {
var state = getSearchState(cm);
if (!state.query) return;
state.query = null;
for (var i = 0; i < state.marked.length; ++i) state.marked[i].clear();
state.marked.length = 0;
});}
var replaceQueryDialog =
'Replace: <input type="text" style="width: 10em"/> <span style="color: #888">(Use /re/ syntax for regexp search)</span>';
var replacementQueryDialog = 'With: <input type="text" style="width: 10em"/>';
var doReplaceConfirm = "Replace? <button>Yes</button> <button>No</button> <button>Stop</button>";
function replace(cm, all) {
dialog(cm, replaceQueryDialog, "Replace:", function(query) {
if (!query) return;
query = parseQuery(query);
dialog(cm, replacementQueryDialog, "Replace with:", function(text) {
if (all) {
cm.compoundChange(function() { cm.operation(function() {
for (var cursor = getSearchCursor(cm, query); cursor.findNext();) {
if (typeof query != "string") {
var match = cm.getRange(cursor.from(), cursor.to()).match(query);
cursor.replace(text.replace(/\$(\d)/, function(w, i) {return match[i];}));
} else cursor.replace(text);
}
});});
} else {
clearSearch(cm);
var cursor = getSearchCursor(cm, query, cm.getCursor());
function advance() {
var start = cursor.from(), match;
if (!(match = cursor.findNext())) {
cursor = getSearchCursor(cm, query);
if (!(match = cursor.findNext()) ||
(start && cursor.from().line == start.line && cursor.from().ch == start.ch)) return;
}
cm.setSelection(cursor.from(), cursor.to());
confirmDialog(cm, doReplaceConfirm, "Replace?",
[function() {doReplace(match);}, advance]);
}
function doReplace(match) {
cursor.replace(typeof query == "string" ? text :
text.replace(/\$(\d)/, function(w, i) {return match[i];}));
advance();
}
advance();
}
});
});
}
CodeMirror.commands.find = function(cm) {clearSearch(cm); doSearch(cm);};
CodeMirror.commands.findNext = doSearch;
CodeMirror.commands.findPrev = function(cm) {doSearch(cm, true);};
CodeMirror.commands.clearSearch = clearSearch;
CodeMirror.commands.replace = replace;
CodeMirror.commands.replaceAll = function(cm) {replace(cm, true);};
})();
(function(){
function SearchCursor(cm, query, pos, caseFold) {
this.atOccurrence = false; this.cm = cm;
if (caseFold == null && typeof query == "string") caseFold = false;
pos = pos ? cm.clipPos(pos) : {line: 0, ch: 0};
this.pos = {from: pos, to: pos};
// The matches method is filled in based on the type of query.
// It takes a position and a direction, and returns an object
// describing the next occurrence of the query, or null if no
// more matches were found.
if (typeof query != "string") { // Regexp match
if (!query.global) query = new RegExp(query.source, query.ignoreCase ? "ig" : "g");
this.matches = function(reverse, pos) {
if (reverse) {
query.lastIndex = 0;
var line = cm.getLine(pos.line).slice(0, pos.ch), match = query.exec(line), start = 0;
while (match) {
start += match.index + 1;
line = line.slice(start);
query.lastIndex = 0;
var newmatch = query.exec(line);
if (newmatch) match = newmatch;
else break;
}
start--;
} else {
query.lastIndex = pos.ch;
var line = cm.getLine(pos.line), match = query.exec(line),
start = match && match.index;
}
if (match)
return {from: {line: pos.line, ch: start},
to: {line: pos.line, ch: start + match[0].length},
match: match};
};
} else { // String query
if (caseFold) query = query.toLowerCase();
var fold = caseFold ? function(str){return str.toLowerCase();} : function(str){return str;};
var target = query.split("\n");
// Different methods for single-line and multi-line queries
if (target.length == 1)
this.matches = function(reverse, pos) {
var line = fold(cm.getLine(pos.line)), len = query.length, match;
if (reverse ? (pos.ch >= len && (match = line.lastIndexOf(query, pos.ch - len)) != -1)
: (match = line.indexOf(query, pos.ch)) != -1)
return {from: {line: pos.line, ch: match},
to: {line: pos.line, ch: match + len}};
};
else
this.matches = function(reverse, pos) {
var ln = pos.line, idx = (reverse ? target.length - 1 : 0), match = target[idx], line = fold(cm.getLine(ln));
var offsetA = (reverse ? line.indexOf(match) + match.length : line.lastIndexOf(match));
if (reverse ? offsetA >= pos.ch || offsetA != match.length
: offsetA <= pos.ch || offsetA != line.length - match.length)
return;
for (;;) {
if (reverse ? !ln : ln == cm.lineCount() - 1) return;
line = fold(cm.getLine(ln += reverse ? -1 : 1));
match = target[reverse ? --idx : ++idx];
if (idx > 0 && idx < target.length - 1) {
if (line != match) return;
else continue;
}
var offsetB = (reverse ? line.lastIndexOf(match) : line.indexOf(match) + match.length);
if (reverse ? offsetB != line.length - match.length : offsetB != match.length)
return;
var start = {line: pos.line, ch: offsetA}, end = {line: ln, ch: offsetB};
return {from: reverse ? end : start, to: reverse ? start : end};
}
};
}
}
SearchCursor.prototype = {
findNext: function() {return this.find(false);},
findPrevious: function() {return this.find(true);},
find: function(reverse) {
var self = this, pos = this.cm.clipPos(reverse ? this.pos.from : this.pos.to);
function savePosAndFail(line) {
var pos = {line: line, ch: 0};
self.pos = {from: pos, to: pos};
self.atOccurrence = false;
return false;
}
for (;;) {
if (this.pos = this.matches(reverse, pos)) {
this.atOccurrence = true;
return this.pos.match || true;
}
if (reverse) {
if (!pos.line) return savePosAndFail(0);
pos = {line: pos.line-1, ch: this.cm.getLine(pos.line-1).length};
}
else {
var maxLine = this.cm.lineCount();
if (pos.line == maxLine - 1) return savePosAndFail(maxLine);
pos = {line: pos.line+1, ch: 0};
}
}
},
from: function() {if (this.atOccurrence) return this.pos.from;},
to: function() {if (this.atOccurrence) return this.pos.to;},
replace: function(newText) {
var self = this;
if (this.atOccurrence)
self.pos.to = this.cm.replaceRange(newText, self.pos.from, self.pos.to);
}
};
CodeMirror.defineExtension("getSearchCursor", function(query, pos, caseFold) {
return new SearchCursor(this, query, pos, caseFold);
});
})();
.CodeMirror-completions {
position: absolute;
z-index: 10;
overflow: hidden;
-webkit-box-shadow: 2px 3px 5px rgba(0,0,0,.2);
-moz-box-shadow: 2px 3px 5px rgba(0,0,0,.2);
box-shadow: 2px 3px 5px rgba(0,0,0,.2);
}
.CodeMirror-completions select {
background: #fafafa;
outline: none;
border: none;
padding: 0;
margin: 0;
font-family: monospace;
}
(function() {
CodeMirror.simpleHint = function(editor, getHints, givenOptions) {
// Determine effective options based on given values and defaults.
var options = {}, defaults = CodeMirror.simpleHint.defaults;
for (var opt in defaults)
if (defaults.hasOwnProperty(opt))
options[opt] = (givenOptions && givenOptions.hasOwnProperty(opt) ? givenOptions : defaults)[opt];
function collectHints(previousToken) {
// We want a single cursor position.
if (editor.somethingSelected()) return;
var tempToken = editor.getTokenAt(editor.getCursor());
// Don't show completions if token has changed and the option is set.
if (options.closeOnTokenChange && previousToken != null &&
(tempToken.start != previousToken.start || tempToken.className != previousToken.className)) {
return;
}
var result = getHints(editor);
if (!result || !result.list.length) return;
var completions = result.list;
function insert(str) {
editor.replaceRange(str, result.from, result.to);
}
// When there is only one completion, use it directly.
if (options.completeSingle && completions.length == 1) {
insert(completions[0]);
return true;
}
// Build the select widget
var complete = document.createElement("div");
complete.className = "CodeMirror-completions";
var sel = complete.appendChild(document.createElement("select"));
// Opera doesn't move the selection when pressing up/down in a
// multi-select, but it does properly support the size property on
// single-selects, so no multi-select is necessary.
if (!window.opera) sel.multiple = true;
for (var i = 0; i < completions.length; ++i) {
var opt = sel.appendChild(document.createElement("option"));
opt.appendChild(document.createTextNode(completions[i]));
}
sel.firstChild.selected = true;
sel.size = Math.min(10, completions.length);
var pos = options.alignWithWord ? editor.charCoords(result.from) : editor.cursorCoords();
complete.style.left = pos.x + "px";
complete.style.top = pos.yBot + "px";
document.body.appendChild(complete);
// If we're at the edge of the screen, then we want the menu to appear on the left of the cursor.
var winW = window.innerWidth || Math.max(document.body.offsetWidth, document.documentElement.offsetWidth);
if(winW - pos.x < sel.clientWidth)
complete.style.left = (pos.x - sel.clientWidth) + "px";
// Hack to hide the scrollbar.
if (completions.length <= 10)
complete.style.width = (sel.clientWidth - 1) + "px";
var done = false;
function close() {
if (done) return;
done = true;
complete.parentNode.removeChild(complete);
}
function pick() {
insert(completions[sel.selectedIndex]);
close();
setTimeout(function(){editor.focus();}, 50);
}
CodeMirror.connect(sel, "blur", close);
CodeMirror.connect(sel, "keydown", function(event) {
var code = event.keyCode;
// Enter
if (code == 13) {CodeMirror.e_stop(event); pick();}
// Escape
else if (code == 27) {CodeMirror.e_stop(event); close(); editor.focus();}
else if (code != 38 && code != 40 && code != 33 && code != 34 && !CodeMirror.isModifierKey(event)) {
close(); editor.focus();
// Pass the event to the CodeMirror instance so that it can handle things like backspace properly.
editor.triggerOnKeyDown(event);
// Don't show completions if the code is backspace and the option is set.
if (!options.closeOnBackspace || code != 8) {
setTimeout(function(){collectHints(tempToken);}, 50);
}
}
});
CodeMirror.connect(sel, "dblclick", pick);
sel.focus();
// Opera sometimes ignores focusing a freshly created node
if (window.opera) setTimeout(function(){if (!done) sel.focus();}, 100);
return true;
}
return collectHints();
};
CodeMirror.simpleHint.defaults = {
closeOnBackspace: true,
closeOnTokenChange: false,
completeSingle: true,
alignWithWord: true
};
})();
(function() {
CodeMirror.xmlHints = [];
CodeMirror.xmlHint = function(cm, simbol) {
if(simbol.length > 0) {
var cursor = cm.getCursor();
cm.replaceSelection(simbol);
cursor = {line: cursor.line, ch: cursor.ch + 1};
cm.setCursor(cursor);
}
// dirty hack for simple-hint to receive getHint event on space
var getTokenAt = editor.getTokenAt;
editor.getTokenAt = function() { return 'disabled'; };
CodeMirror.simpleHint(cm, getHint);
editor.getTokenAt = getTokenAt;
};
var getHint = function(cm) {
var cursor = cm.getCursor();
if (cursor.ch > 0) {
var text = cm.getRange({line: 0, ch: 0}, cursor);
var typed = '';
var simbol = '';
for(var i = text.length - 1; i >= 0; i--) {
if(text[i] == ' ' || text[i] == '<') {
simbol = text[i];
break;
}
else {
typed = text[i] + typed;
}
}
text = text.slice(0, text.length - typed.length);
var path = getActiveElement(cm, text) + simbol;
var hints = CodeMirror.xmlHints[path];
if(typeof hints === 'undefined')
hints = [''];
else {
hints = hints.slice(0);
for (var i = hints.length - 1; i >= 0; i--) {
if(hints[i].indexOf(typed) != 0)
hints.splice(i, 1);
}
}
return {
list: hints,
from: { line: cursor.line, ch: cursor.ch - typed.length },
to: cursor
};
};
};
var getActiveElement = function(codeMirror, text) {
var element = '';
if(text.length >= 0) {
var regex = new RegExp('<([^!?][^\\s/>]*).*?>', 'g');
var matches = [];
var match;
while ((match = regex.exec(text)) != null) {
matches.push({
tag: match[1],
selfclose: (match[0].slice(match[0].length - 2) === '/>')
});
}
for (var i = matches.length - 1, skip = 0; i >= 0; i--) {
var item = matches[i];
if (item.tag[0] == '/')
{
skip++;
}
else if (item.selfclose == false)
{
if (skip > 0)
{
skip--;
}
else
{
element = '<' + item.tag + '>' + element;
}
}
}
element += getOpenTag(text);
}
return element;
};
var getOpenTag = function(text) {
var open = text.lastIndexOf('<');
var close = text.lastIndexOf('>');
if (close < open)
{
text = text.slice(open);
if(text != '<') {
var space = text.indexOf(' ');
if(space < 0)
space = text.indexOf('\t');
if(space < 0)
space = text.indexOf('\n');
if (space < 0)
space = text.length;
return text.slice(0, space);
}
}
return '';
};
})();
Copyright (C) 2012 by Marijn Haverbeke <marijnh@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Please note that some subdirectories of the CodeMirror distribution
include their own LICENSE files, and are released under different
licences.
CodeMirror.defineMode("clike", function(config, parserConfig) {
var indentUnit = config.indentUnit,
keywords = parserConfig.keywords || {},
builtin = parserConfig.builtin || {},
blockKeywords = parserConfig.blockKeywords || {},
atoms = parserConfig.atoms || {},
hooks = parserConfig.hooks || {},
multiLineStrings = parserConfig.multiLineStrings;
var isOperatorChar = /[+\-*&%=<>!?|\/]/;
var curPunc;
function tokenBase(stream, state) {
var ch = stream.next();
if (hooks[ch]) {
var result = hooks[ch](stream, state);
if (result !== false) return result;
}
if (ch == '"' || ch == "'") {
state.tokenize = tokenString(ch);
return state.tokenize(stream, state);
}
if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
curPunc = ch;
return null;
}
if (/\d/.test(ch)) {
stream.eatWhile(/[\w\.]/);
return "number";
}
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\$_]/);
var cur = stream.current();
if (keywords.propertyIsEnumerable(cur)) {
if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
return "keyword";
}
if (builtin.propertyIsEnumerable(cur)) {
if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
return "builtin";
}
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 && next == "\\";
}
if (end || !(escaped || multiLineStrings))
state.tokenize = null;
return "string";
};
}
function tokenComment(stream, state) {
var maybeEnd = false, ch;
while (ch = stream.next()) {
if (ch == "/" && maybeEnd) {
state.tokenize = null;
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) {
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 (stream.eatSpace()) return null;
curPunc = null;
var style = (state.tokenize || tokenBase)(stream, state);
if (style == "comment" || style == "meta") return style;
if (ctx.align == null) ctx.align = true;
if ((curPunc == ";" || curPunc == ":") && ctx.type == "statement") popContext(state);
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;
return style;
},
indent: function(state, textAfter) {
if (state.tokenize == tokenComment) return CodeMirror.Pass;
if (state.tokenize != tokenBase && state.tokenize != null) return 0;
var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev;
var closing = firstChar == ctx.type;
if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : indentUnit);
else if (ctx.align) return ctx.column + (closing ? 0 : 1);
else return ctx.indented + (closing ? 0 : indentUnit);
},
electricChars: "{}"
};
});
(function() {
function words(str) {
var obj = {}, words = str.split(" ");
for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
return obj;
}
var cKeywords = "auto if break int case long char register continue return default short do sizeof " +
"double static else struct entry switch extern typedef float union for unsigned " +
"goto while enum void const signed volatile";
function cppHook(stream, state) {
if (!state.startOfLine) return false;
stream.skipToEnd();
return "meta";
}
// C#-style strings where "" escapes a quote.
function tokenAtString(stream, state) {
var next;
while ((next = stream.next()) != null) {
if (next == '"' && !stream.eat('"')) {
state.tokenize = null;
break;
}
}
return "string";
}
function mimes(ms, mode) {
for (var i = 0; i < ms.length; ++i) CodeMirror.defineMIME(ms[i], mode);
}
mimes(["text/x-csrc", "text/x-c", "text/x-chdr"], {
name: "clike",
keywords: words(cKeywords),
blockKeywords: words("case do else for if switch while struct"),
atoms: words("null"),
hooks: {"#": cppHook}
});
mimes(["text/x-c++src", "text/x-c++hdr"], {
name: "clike",
keywords: words(cKeywords + " asm dynamic_cast namespace reinterpret_cast try bool explicit new " +
"static_cast typeid catch operator template typename class friend private " +
"this using const_cast inline public throw virtual delete mutable protected " +
"wchar_t"),
blockKeywords: words("catch class do else finally for if struct switch try while"),
atoms: words("true false null"),
hooks: {"#": cppHook}
});
CodeMirror.defineMIME("text/x-java", {
name: "clike",
keywords: words("abstract assert boolean break byte case catch char class const continue default " +
"do double else enum extends final finally float for goto if implements import " +
"instanceof int interface long native new package private protected public " +
"return short static strictfp super switch synchronized this throw throws transient " +
"try void volatile while"),
blockKeywords: words("catch class do else finally for if switch try while"),
atoms: words("true false null"),
hooks: {
"@": function(stream, state) {
stream.eatWhile(/[\w\$_]/);
return "meta";
}
}
});
CodeMirror.defineMIME("text/x-csharp", {
name: "clike",
keywords: words("abstract as base break case catch checked class const continue" +
" default delegate do else enum event explicit extern finally fixed for" +
" foreach goto if implicit in interface internal is lock namespace new" +
" operator out override params private protected public readonly ref return sealed" +
" sizeof stackalloc static struct switch this throw try typeof unchecked" +
" unsafe using virtual void volatile while add alias ascending descending dynamic from get" +
" global group into join let orderby partial remove select set value var yield"),
blockKeywords: words("catch class do else finally for foreach if struct switch try while"),
builtin: words("Boolean Byte Char DateTime DateTimeOffset Decimal Double" +
" Guid Int16 Int32 Int64 Object SByte Single String TimeSpan UInt16 UInt32" +
" UInt64 bool byte char decimal double short int long object" +
" sbyte float string ushort uint ulong"),
atoms: words("true false null"),
hooks: {
"@": function(stream, state) {
if (stream.eat('"')) {
state.tokenize = tokenAtString;
return tokenAtString(stream, state);
}
stream.eatWhile(/[\w\$_]/);
return "meta";
}
}
});
CodeMirror.defineMIME("text/x-scala", {
name: "clike",
keywords: words(
/* scala */
"abstract case catch class def do else extends false final finally for forSome if " +
"implicit import lazy match new null object override package private protected return " +
"sealed super this throw trait try trye type val var while with yield _ : = => <- <: " +
"<% >: # @ " +
/* package scala */
"assert assume require print println printf readLine readBoolean readByte readShort " +
"readChar readInt readLong readFloat readDouble " +
"AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either " +
"Enumeration Equiv Error Exception Fractional Function IndexedSeq Integral Iterable " +
"Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering " +
"Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder " +
"StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector :: #:: " +
/* package java.lang */
"Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " +
"Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " +
"Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " +
"StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void"
),
blockKeywords: words("catch class do else finally for forSome if match switch try while"),
atoms: words("true false null"),
hooks: {
"@": function(stream, state) {
stream.eatWhile(/[\w\$_]/);
return "meta";
}
}
});
}());
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: C-like mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="clike.js"></script>
<link rel="stylesheet" href="../../doc/docs.css">
<style>.CodeMirror {border: 2px inset #dee;}</style>
</head>
<body>
<h1>CodeMirror: C-like mode</h1>
<form><textarea id="code" name="code">
/* C demo code */
#include <zmq.h>
#include <pthread.h>
#include <semaphore.h>
#include <time.h>
#include <stdio.h>
#include <fcntl.h>
#include <malloc.h>
typedef struct {
void* arg_socket;
zmq_msg_t* arg_msg;
char* arg_string;
unsigned long arg_len;
int arg_int, arg_command;
int signal_fd;
int pad;
void* context;
sem_t sem;
} acl_zmq_context;
#define p(X) (context->arg_##X)
void* zmq_thread(void* context_pointer) {
acl_zmq_context* context = (acl_zmq_context*)context_pointer;
char ok = 'K', err = 'X';
int res;
while (1) {
while ((res = sem_wait(&amp;context->sem)) == EINTR);
if (res) {write(context->signal_fd, &amp;err, 1); goto cleanup;}
switch(p(command)) {
case 0: goto cleanup;
case 1: p(socket) = zmq_socket(context->context, p(int)); break;
case 2: p(int) = zmq_close(p(socket)); break;
case 3: p(int) = zmq_bind(p(socket), p(string)); break;
case 4: p(int) = zmq_connect(p(socket), p(string)); break;
case 5: p(int) = zmq_getsockopt(p(socket), p(int), (void*)p(string), &amp;p(len)); break;
case 6: p(int) = zmq_setsockopt(p(socket), p(int), (void*)p(string), p(len)); break;
case 7: p(int) = zmq_send(p(socket), p(msg), p(int)); break;
case 8: p(int) = zmq_recv(p(socket), p(msg), p(int)); break;
case 9: p(int) = zmq_poll(p(socket), p(int), p(len)); break;
}
p(command) = errno;
write(context->signal_fd, &amp;ok, 1);
}
cleanup:
close(context->signal_fd);
free(context_pointer);
return 0;
}
void* zmq_thread_init(void* zmq_context, int signal_fd) {
acl_zmq_context* context = malloc(sizeof(acl_zmq_context));
pthread_t thread;
context->context = zmq_context;
context->signal_fd = signal_fd;
sem_init(&amp;context->sem, 1, 0);
pthread_create(&amp;thread, 0, &amp;zmq_thread, context);
pthread_detach(thread);
return context;
}
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
matchBrackets: true,
mode: "text/x-csrc"
});
</script>
<p>Simple mode that tries to handle C-like languages as well as it
can. Takes two configuration parameters: <code>keywords</code>, an
object whose property names are the keywords in the language,
and <code>useCPP</code>, which determines whether C preprocessor
directives are recognized.</p>
<p><strong>MIME types defined:</strong> <code>text/x-csrc</code>
(C code), <code>text/x-c++src</code> (C++
code), <code>text/x-java</code> (Java
code), <code>text/x-csharp</code> (C#).</p>
</body>
</html>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: C-like mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<link rel="stylesheet" href="../../theme/ambiance.css">
<script src="../../lib/codemirror.js"></script>
<script src="clike.js"></script>
<link rel="stylesheet" href="../../doc/docs.css">
<style>
body
{
margin: 0;
padding: 0;
max-width:inherit;
height: 100%;
}
html, form, .CodeMirror, .CodeMirror-scroll
{
height: 100%;
}
</style>
</head>
<body>
<form>
<textarea id="code" name="code">
/* __ *\
** ________ ___ / / ___ Scala API **
** / __/ __// _ | / / / _ | (c) 2003-2011, LAMP/EPFL **
** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ **
** /____/\___/_/ |_/____/_/ | | **
** |/ **
\* */
package scala.collection
import generic._
import mutable.{ Builder, ListBuffer }
import annotation.{tailrec, migration, bridge}
import annotation.unchecked.{ uncheckedVariance => uV }
import parallel.ParIterable
/** A template trait for traversable collections of type `Traversable[A]`.
*
* $traversableInfo
* @define mutability
* @define traversableInfo
* This is a base trait of all kinds of $mutability Scala collections. It
* implements the behavior common to all collections, in terms of a method
* `foreach` with signature:
* {{{
* def foreach[U](f: Elem => U): Unit
* }}}
* Collection classes mixing in this trait provide a concrete
* `foreach` method which traverses all the
* elements contained in the collection, applying a given function to each.
* They also need to provide a method `newBuilder`
* which creates a builder for collections of the same kind.
*
* A traversable class might or might not have two properties: strictness
* and orderedness. Neither is represented as a type.
*
* The instances of a strict collection class have all their elements
* computed before they can be used as values. By contrast, instances of
* a non-strict collection class may defer computation of some of their
* elements until after the instance is available as a value.
* A typical example of a non-strict collection class is a
* <a href="../immutable/Stream.html" target="ContentFrame">
* `scala.collection.immutable.Stream`</a>.
* A more general class of examples are `TraversableViews`.
*
* If a collection is an instance of an ordered collection class, traversing
* its elements with `foreach` will always visit elements in the
* same order, even for different runs of the program. If the class is not
* ordered, `foreach` can visit elements in different orders for
* different runs (but it will keep the same order in the same run).'
*
* A typical example of a collection class which is not ordered is a
* `HashMap` of objects. The traversal order for hash maps will
* depend on the hash codes of its elements, and these hash codes might
* differ from one run to the next. By contrast, a `LinkedHashMap`
* is ordered because it's `foreach` method visits elements in the
* order they were inserted into the `HashMap`.
*
* @author Martin Odersky
* @version 2.8
* @since 2.8
* @tparam A the element type of the collection
* @tparam Repr the type of the actual collection containing the elements.
*
* @define Coll Traversable
* @define coll traversable collection
*/
trait TraversableLike[+A, +Repr] extends HasNewBuilder[A, Repr]
with FilterMonadic[A, Repr]
with TraversableOnce[A]
with GenTraversableLike[A, Repr]
with Parallelizable[A, ParIterable[A]]
{
self =>
import Traversable.breaks._
/** The type implementing this traversable */
protected type Self = Repr
/** The collection of type $coll underlying this `TraversableLike` object.
* By default this is implemented as the `TraversableLike` object itself,
* but this can be overridden.
*/
def repr: Repr = this.asInstanceOf[Repr]
/** The underlying collection seen as an instance of `$Coll`.
* By default this is implemented as the current collection object itself,
* but this can be overridden.
*/
protected[this] def thisCollection: Traversable[A] = this.asInstanceOf[Traversable[A]]
/** A conversion from collections of type `Repr` to `$Coll` objects.
* By default this is implemented as just a cast, but this can be overridden.
*/
protected[this] def toCollection(repr: Repr): Traversable[A] = repr.asInstanceOf[Traversable[A]]
/** Creates a new builder for this collection type.
*/
protected[this] def newBuilder: Builder[A, Repr]
protected[this] def parCombiner = ParIterable.newCombiner[A]
/** Applies a function `f` to all elements of this $coll.
*
* Note: this method underlies the implementation of most other bulk operations.
* It's important to implement this method in an efficient way.
*
*
* @param f the function that is applied for its side-effect to every element.
* The result of function `f` is discarded.
*
* @tparam U the type parameter describing the result of function `f`.
* This result will always be ignored. Typically `U` is `Unit`,
* but this is not necessary.
*
* @usecase def foreach(f: A => Unit): Unit
*/
def foreach[U](f: A => U): Unit
/** Tests whether this $coll is empty.
*
* @return `true` if the $coll contain no elements, `false` otherwise.
*/
def isEmpty: Boolean = {
var result = true
breakable {
for (x <- this) {
result = false
break
}
}
result
}
/** Tests whether this $coll is known to have a finite size.
* All strict collections are known to have finite size. For a non-strict collection
* such as `Stream`, the predicate returns `true` if all elements have been computed.
* It returns `false` if the stream is not yet evaluated to the end.
*
* Note: many collection methods will not work on collections of infinite sizes.
*
* @return `true` if this collection is known to have finite size, `false` otherwise.
*/
def hasDefiniteSize = true
def ++[B >: A, That](that: GenTraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
val b = bf(repr)
if (that.isInstanceOf[IndexedSeqLike[_, _]]) b.sizeHint(this, that.seq.size)
b ++= thisCollection
b ++= that.seq
b.result
}
@bridge
def ++[B >: A, That](that: TraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That =
++(that: GenTraversableOnce[B])(bf)
/** Concatenates this $coll with the elements of a traversable collection.
* It differs from ++ in that the right operand determines the type of the
* resulting collection rather than the left one.
*
* @param that the traversable to append.
* @tparam B the element type of the returned collection.
* @tparam That $thatinfo
* @param bf $bfinfo
* @return a new collection of type `That` which contains all elements
* of this $coll followed by all elements of `that`.
*
* @usecase def ++:[B](that: TraversableOnce[B]): $Coll[B]
*
* @return a new $coll which contains all elements of this $coll
* followed by all elements of `that`.
*/
def ++:[B >: A, That](that: TraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
val b = bf(repr)
if (that.isInstanceOf[IndexedSeqLike[_, _]]) b.sizeHint(this, that.size)
b ++= that
b ++= thisCollection
b.result
}
/** This overload exists because: for the implementation of ++: we should reuse
* that of ++ because many collections override it with more efficient versions.
* Since TraversableOnce has no '++' method, we have to implement that directly,
* but Traversable and down can use the overload.
*/
def ++:[B >: A, That](that: Traversable[B])(implicit bf: CanBuildFrom[Repr, B, That]): That =
(that ++ seq)(breakOut)
def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
val b = bf(repr)
b.sizeHint(this)
for (x <- this) b += f(x)
b.result
}
def flatMap[B, That](f: A => GenTraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
val b = bf(repr)
for (x <- this) b ++= f(x).seq
b.result
}
/** Selects all elements of this $coll which satisfy a predicate.
*
* @param p the predicate used to test elements.
* @return a new $coll consisting of all elements of this $coll that satisfy the given
* predicate `p`. The order of the elements is preserved.
*/
def filter(p: A => Boolean): Repr = {
val b = newBuilder
for (x <- this)
if (p(x)) b += x
b.result
}
/** Selects all elements of this $coll which do not satisfy a predicate.
*
* @param p the predicate used to test elements.
* @return a new $coll consisting of all elements of this $coll that do not satisfy the given
* predicate `p`. The order of the elements is preserved.
*/
def filterNot(p: A => Boolean): Repr = filter(!p(_))
def collect[B, That](pf: PartialFunction[A, B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
val b = bf(repr)
for (x <- this) if (pf.isDefinedAt(x)) b += pf(x)
b.result
}
/** Builds a new collection by applying an option-valued function to all
* elements of this $coll on which the function is defined.
*
* @param f the option-valued function which filters and maps the $coll.
* @tparam B the element type of the returned collection.
* @tparam That $thatinfo
* @param bf $bfinfo
* @return a new collection of type `That` resulting from applying the option-valued function
* `f` to each element and collecting all defined results.
* The order of the elements is preserved.
*
* @usecase def filterMap[B](f: A => Option[B]): $Coll[B]
*
* @param pf the partial function which filters and maps the $coll.
* @return a new $coll resulting from applying the given option-valued function
* `f` to each element and collecting all defined results.
* The order of the elements is preserved.
def filterMap[B, That](f: A => Option[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
val b = bf(repr)
for (x <- this)
f(x) match {
case Some(y) => b += y
case _ =>
}
b.result
}
*/
/** Partitions this $coll in two ${coll}s according to a predicate.
*
* @param p the predicate on which to partition.
* @return a pair of ${coll}s: the first $coll consists of all elements that
* satisfy the predicate `p` and the second $coll consists of all elements
* that don't. The relative order of the elements in the resulting ${coll}s
* is the same as in the original $coll.
*/
def partition(p: A => Boolean): (Repr, Repr) = {
val l, r = newBuilder
for (x <- this) (if (p(x)) l else r) += x
(l.result, r.result)
}
def groupBy[K](f: A => K): immutable.Map[K, Repr] = {
val m = mutable.Map.empty[K, Builder[A, Repr]]
for (elem <- this) {
val key = f(elem)
val bldr = m.getOrElseUpdate(key, newBuilder)
bldr += elem
}
val b = immutable.Map.newBuilder[K, Repr]
for ((k, v) <- m)
b += ((k, v.result))
b.result
}
/** Tests whether a predicate holds for all elements of this $coll.
*
* $mayNotTerminateInf
*
* @param p the predicate used to test elements.
* @return `true` if the given predicate `p` holds for all elements
* of this $coll, otherwise `false`.
*/
def forall(p: A => Boolean): Boolean = {
var result = true
breakable {
for (x <- this)
if (!p(x)) { result = false; break }
}
result
}
/** Tests whether a predicate holds for some of the elements of this $coll.
*
* $mayNotTerminateInf
*
* @param p the predicate used to test elements.
* @return `true` if the given predicate `p` holds for some of the
* elements of this $coll, otherwise `false`.
*/
def exists(p: A => Boolean): Boolean = {
var result = false
breakable {
for (x <- this)
if (p(x)) { result = true; break }
}
result
}
/** Finds the first element of the $coll satisfying a predicate, if any.
*
* $mayNotTerminateInf
* $orderDependent
*
* @param p the predicate used to test elements.
* @return an option value containing the first element in the $coll
* that satisfies `p`, or `None` if none exists.
*/
def find(p: A => Boolean): Option[A] = {
var result: Option[A] = None
breakable {
for (x <- this)
if (p(x)) { result = Some(x); break }
}
result
}
def scan[B >: A, That](z: B)(op: (B, B) => B)(implicit cbf: CanBuildFrom[Repr, B, That]): That = scanLeft(z)(op)
def scanLeft[B, That](z: B)(op: (B, A) => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
val b = bf(repr)
b.sizeHint(this, 1)
var acc = z
b += acc
for (x <- this) { acc = op(acc, x); b += acc }
b.result
}
@migration(2, 9,
"This scanRight definition has changed in 2.9.\n" +
"The previous behavior can be reproduced with scanRight.reverse."
)
def scanRight[B, That](z: B)(op: (A, B) => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
var scanned = List(z)
var acc = z
for (x <- reversed) {
acc = op(x, acc)
scanned ::= acc
}
val b = bf(repr)
for (elem <- scanned) b += elem
b.result
}
/** Selects the first element of this $coll.
* $orderDependent
* @return the first element of this $coll.
* @throws `NoSuchElementException` if the $coll is empty.
*/
def head: A = {
var result: () => A = () => throw new NoSuchElementException
breakable {
for (x <- this) {
result = () => x
break
}
}
result()
}
/** Optionally selects the first element.
* $orderDependent
* @return the first element of this $coll if it is nonempty, `None` if it is empty.
*/
def headOption: Option[A] = if (isEmpty) None else Some(head)
/** Selects all elements except the first.
* $orderDependent
* @return a $coll consisting of all elements of this $coll
* except the first one.
* @throws `UnsupportedOperationException` if the $coll is empty.
*/
override def tail: Repr = {
if (isEmpty) throw new UnsupportedOperationException("empty.tail")
drop(1)
}
/** Selects the last element.
* $orderDependent
* @return The last element of this $coll.
* @throws NoSuchElementException If the $coll is empty.
*/
def last: A = {
var lst = head
for (x <- this)
lst = x
lst
}
/** Optionally selects the last element.
* $orderDependent
* @return the last element of this $coll$ if it is nonempty, `None` if it is empty.
*/
def lastOption: Option[A] = if (isEmpty) None else Some(last)
/** Selects all elements except the last.
* $orderDependent
* @return a $coll consisting of all elements of this $coll
* except the last one.
* @throws `UnsupportedOperationException` if the $coll is empty.
*/
def init: Repr = {
if (isEmpty) throw new UnsupportedOperationException("empty.init")
var lst = head
var follow = false
val b = newBuilder
b.sizeHint(this, -1)
for (x <- this.seq) {
if (follow) b += lst
else follow = true
lst = x
}
b.result
}
def take(n: Int): Repr = slice(0, n)
def drop(n: Int): Repr =
if (n <= 0) {
val b = newBuilder
b.sizeHint(this)
b ++= thisCollection result
}
else sliceWithKnownDelta(n, Int.MaxValue, -n)
def slice(from: Int, until: Int): Repr = sliceWithKnownBound(math.max(from, 0), until)
// Precondition: from >= 0, until > 0, builder already configured for building.
private[this] def sliceInternal(from: Int, until: Int, b: Builder[A, Repr]): Repr = {
var i = 0
breakable {
for (x <- this.seq) {
if (i >= from) b += x
i += 1
if (i >= until) break
}
}
b.result
}
// Precondition: from >= 0
private[scala] def sliceWithKnownDelta(from: Int, until: Int, delta: Int): Repr = {
val b = newBuilder
if (until <= from) b.result
else {
b.sizeHint(this, delta)
sliceInternal(from, until, b)
}
}
// Precondition: from >= 0
private[scala] def sliceWithKnownBound(from: Int, until: Int): Repr = {
val b = newBuilder
if (until <= from) b.result
else {
b.sizeHintBounded(until - from, this)
sliceInternal(from, until, b)
}
}
def takeWhile(p: A => Boolean): Repr = {
val b = newBuilder
breakable {
for (x <- this) {
if (!p(x)) break
b += x
}
}
b.result
}
def dropWhile(p: A => Boolean): Repr = {
val b = newBuilder
var go = false
for (x <- this) {
if (!p(x)) go = true
if (go) b += x
}
b.result
}
def span(p: A => Boolean): (Repr, Repr) = {
val l, r = newBuilder
var toLeft = true
for (x <- this) {
toLeft = toLeft && p(x)
(if (toLeft) l else r) += x
}
(l.result, r.result)
}
def splitAt(n: Int): (Repr, Repr) = {
val l, r = newBuilder
l.sizeHintBounded(n, this)
if (n >= 0) r.sizeHint(this, -n)
var i = 0
for (x <- this) {
(if (i < n) l else r) += x
i += 1
}
(l.result, r.result)
}
/** Iterates over the tails of this $coll. The first value will be this
* $coll and the final one will be an empty $coll, with the intervening
* values the results of successive applications of `tail`.
*
* @return an iterator over all the tails of this $coll
* @example `List(1,2,3).tails = Iterator(List(1,2,3), List(2,3), List(3), Nil)`
*/
def tails: Iterator[Repr] = iterateUntilEmpty(_.tail)
/** Iterates over the inits of this $coll. The first value will be this
* $coll and the final one will be an empty $coll, with the intervening
* values the results of successive applications of `init`.
*
* @return an iterator over all the inits of this $coll
* @example `List(1,2,3).inits = Iterator(List(1,2,3), List(1,2), List(1), Nil)`
*/
def inits: Iterator[Repr] = iterateUntilEmpty(_.init)
/** Copies elements of this $coll to an array.
* Fills the given array `xs` with at most `len` elements of
* this $coll, starting at position `start`.
* Copying will stop once either the end of the current $coll is reached,
* or the end of the array is reached, or `len` elements have been copied.
*
* $willNotTerminateInf
*
* @param xs the array to fill.
* @param start the starting index.
* @param len the maximal number of elements to copy.
* @tparam B the type of the elements of the array.
*
*
* @usecase def copyToArray(xs: Array[A], start: Int, len: Int): Unit
*/
def copyToArray[B >: A](xs: Array[B], start: Int, len: Int) {
var i = start
val end = (start + len) min xs.length
breakable {
for (x <- this) {
if (i >= end) break
xs(i) = x
i += 1
}
}
}
def toTraversable: Traversable[A] = thisCollection
def toIterator: Iterator[A] = toStream.iterator
def toStream: Stream[A] = toBuffer.toStream
/** Converts this $coll to a string.
*
* @return a string representation of this collection. By default this
* string consists of the `stringPrefix` of this $coll,
* followed by all elements separated by commas and enclosed in parentheses.
*/
override def toString = mkString(stringPrefix + "(", ", ", ")")
/** Defines the prefix of this object's `toString` representation.
*
* @return a string representation which starts the result of `toString`
* applied to this $coll. By default the string prefix is the
* simple name of the collection class $coll.
*/
def stringPrefix : String = {
var string = repr.asInstanceOf[AnyRef].getClass.getName
val idx1 = string.lastIndexOf('.' : Int)
if (idx1 != -1) string = string.substring(idx1 + 1)
val idx2 = string.indexOf('$')
if (idx2 != -1) string = string.substring(0, idx2)
string
}
/** Creates a non-strict view of this $coll.
*
* @return a non-strict view of this $coll.
*/
def view = new TraversableView[A, Repr] {
protected lazy val underlying = self.repr
override def foreach[U](f: A => U) = self foreach f
}
/** Creates a non-strict view of a slice of this $coll.
*
* Note: the difference between `view` and `slice` is that `view` produces
* a view of the current $coll, whereas `slice` produces a new $coll.
*
* Note: `view(from, to)` is equivalent to `view.slice(from, to)`
* $orderDependent
*
* @param from the index of the first element of the view
* @param until the index of the element following the view
* @return a non-strict view of a slice of this $coll, starting at index `from`
* and extending up to (but not including) index `until`.
*/
def view(from: Int, until: Int): TraversableView[A, Repr] = view.slice(from, until)
/** Creates a non-strict filter of this $coll.
*
* Note: the difference between `c filter p` and `c withFilter p` is that
* the former creates a new collection, whereas the latter only
* restricts the domain of subsequent `map`, `flatMap`, `foreach`,
* and `withFilter` operations.
* $orderDependent
*
* @param p the predicate used to test elements.
* @return an object of class `WithFilter`, which supports
* `map`, `flatMap`, `foreach`, and `withFilter` operations.
* All these operations apply to those elements of this $coll which
* satisfy the predicate `p`.
*/
def withFilter(p: A => Boolean): FilterMonadic[A, Repr] = new WithFilter(p)
/** A class supporting filtered operations. Instances of this class are
* returned by method `withFilter`.
*/
class WithFilter(p: A => Boolean) extends FilterMonadic[A, Repr] {
/** Builds a new collection by applying a function to all elements of the
* outer $coll containing this `WithFilter` instance that satisfy predicate `p`.
*
* @param f the function to apply to each element.
* @tparam B the element type of the returned collection.
* @tparam That $thatinfo
* @param bf $bfinfo
* @return a new collection of type `That` resulting from applying
* the given function `f` to each element of the outer $coll
* that satisfies predicate `p` and collecting the results.
*
* @usecase def map[B](f: A => B): $Coll[B]
*
* @return a new $coll resulting from applying the given function
* `f` to each element of the outer $coll that satisfies
* predicate `p` and collecting the results.
*/
def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
val b = bf(repr)
for (x <- self)
if (p(x)) b += f(x)
b.result
}
/** Builds a new collection by applying a function to all elements of the
* outer $coll containing this `WithFilter` instance that satisfy
* predicate `p` and concatenating the results.
*
* @param f the function to apply to each element.
* @tparam B the element type of the returned collection.
* @tparam That $thatinfo
* @param bf $bfinfo
* @return a new collection of type `That` resulting from applying
* the given collection-valued function `f` to each element
* of the outer $coll that satisfies predicate `p` and
* concatenating the results.
*
* @usecase def flatMap[B](f: A => TraversableOnce[B]): $Coll[B]
*
* @return a new $coll resulting from applying the given collection-valued function
* `f` to each element of the outer $coll that satisfies predicate `p` and concatenating the results.
*/
def flatMap[B, That](f: A => GenTraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
val b = bf(repr)
for (x <- self)
if (p(x)) b ++= f(x).seq
b.result
}
/** Applies a function `f` to all elements of the outer $coll containing
* this `WithFilter` instance that satisfy predicate `p`.
*
* @param f the function that is applied for its side-effect to every element.
* The result of function `f` is discarded.
*
* @tparam U the type parameter describing the result of function `f`.
* This result will always be ignored. Typically `U` is `Unit`,
* but this is not necessary.
*
* @usecase def foreach(f: A => Unit): Unit
*/
def foreach[U](f: A => U): Unit =
for (x <- self)
if (p(x)) f(x)
/** Further refines the filter for this $coll.
*
* @param q the predicate used to test elements.
* @return an object of class `WithFilter`, which supports
* `map`, `flatMap`, `foreach`, and `withFilter` operations.
* All these operations apply to those elements of this $coll which
* satisfy the predicate `q` in addition to the predicate `p`.
*/
def withFilter(q: A => Boolean): WithFilter =
new WithFilter(x => p(x) && q(x))
}
// A helper for tails and inits.
private def iterateUntilEmpty(f: Traversable[A @uV] => Traversable[A @uV]): Iterator[Repr] = {
val it = Iterator.iterate(thisCollection)(f) takeWhile (x => !x.isEmpty)
it ++ Iterator(Nil) map (newBuilder ++= _ result)
}
}
</textarea>
</form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
matchBrackets: true,
theme: "ambiance",
mode: "text/x-scala"
});
</script>
</body>
</html>
/**
* Author: Hans Engel
* Branched from CodeMirror's Scheme mode (by Koh Zi Han, based on implementation by Koh Zi Chun)
*/
CodeMirror.defineMode("clojure", function (config, mode) {
var BUILTIN = "builtin", COMMENT = "comment", STRING = "string", TAG = "tag",
ATOM = "atom", NUMBER = "number", BRACKET = "bracket", KEYWORD = "keyword";
var INDENT_WORD_SKIP = 2, KEYWORDS_SKIP = 1;
function makeKeywords(str) {
var obj = {}, words = str.split(" ");
for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
return obj;
}
var atoms = makeKeywords("true false nil");
var keywords = makeKeywords(
"defn defn- def def- defonce defmulti defmethod defmacro defstruct deftype defprotocol defrecord defproject deftest slice defalias defhinted defmacro- defn-memo defnk defnk defonce- defunbound defunbound- defvar defvar- let letfn do case cond condp for loop recur when when-not when-let when-first if if-let if-not . .. -> ->> doto and or dosync doseq dotimes dorun doall load import unimport ns in-ns refer try catch finally throw with-open with-local-vars binding gen-class gen-and-load-class gen-and-save-class handler-case handle");
var builtins = makeKeywords(
"* *1 *2 *3 *agent* *allow-unresolved-vars* *assert *clojure-version* *command-line-args* *compile-files* *compile-path* *e *err* *file* *flush-on-newline* *in* *macro-meta* *math-context* *ns* *out* *print-dup* *print-length* *print-level* *print-meta* *print-readably* *read-eval* *source-path* *use-context-classloader* *warn-on-reflection* + - / < <= = == > >= accessor aclone agent agent-errors aget alength alias all-ns alter alter-meta! alter-var-root amap ancestors and apply areduce array-map aset aset-boolean aset-byte aset-char aset-double aset-float aset-int aset-long aset-short assert assoc assoc! assoc-in associative? atom await await-for await1 bases bean bigdec bigint binding bit-and bit-and-not bit-clear bit-flip bit-not bit-or bit-set bit-shift-left bit-shift-right bit-test bit-xor boolean boolean-array booleans bound-fn bound-fn* butlast byte byte-array bytes case cast char char-array char-escape-string char-name-string char? chars chunk chunk-append chunk-buffer chunk-cons chunk-first chunk-next chunk-rest chunked-seq? class class? clear-agent-errors clojure-version coll? comment commute comp comparator compare compare-and-set! compile complement concat cond condp conj conj! cons constantly construct-proxy contains? count counted? create-ns create-struct cycle dec decimal? declare definline defmacro defmethod defmulti defn defn- defonce defstruct delay delay? deliver deref derive descendants destructure disj disj! dissoc dissoc! distinct distinct? doall doc dorun doseq dosync dotimes doto double double-array doubles drop drop-last drop-while empty empty? ensure enumeration-seq eval even? every? extend extend-protocol extend-type extends? extenders false? ffirst file-seq filter find find-doc find-ns find-var first float float-array float? floats flush fn fn? fnext for force format future future-call future-cancel future-cancelled? future-done? future? gen-class gen-interface gensym get get-in get-method get-proxy-class get-thread-bindings get-validator hash hash-map hash-set identical? identity if-let if-not ifn? import in-ns inc init-proxy instance? int int-array integer? interleave intern interpose into into-array ints io! isa? iterate iterator-seq juxt key keys keyword keyword? last lazy-cat lazy-seq let letfn line-seq list list* list? load load-file load-reader load-string loaded-libs locking long long-array longs loop macroexpand macroexpand-1 make-array make-hierarchy map map? mapcat max max-key memfn memoize merge merge-with meta method-sig methods min min-key mod name namespace neg? newline next nfirst nil? nnext not not-any? not-empty not-every? not= ns ns-aliases ns-imports ns-interns ns-map ns-name ns-publics ns-refers ns-resolve ns-unalias ns-unmap nth nthnext num number? odd? or parents partial partition pcalls peek persistent! pmap pop pop! pop-thread-bindings pos? pr pr-str prefer-method prefers primitives-classnames print print-ctor print-doc print-dup print-method print-namespace-doc print-simple print-special-doc print-str printf println println-str prn prn-str promise proxy proxy-call-with-super proxy-mappings proxy-name proxy-super push-thread-bindings pvalues quot rand rand-int range ratio? rational? rationalize re-find re-groups re-matcher re-matches re-pattern re-seq read read-line read-string reify reduce ref ref-history-count ref-max-history ref-min-history ref-set refer refer-clojure release-pending-sends rem remove remove-method remove-ns repeat repeatedly replace replicate require reset! reset-meta! resolve rest resultset-seq reverse reversible? rseq rsubseq satisfies? second select-keys send send-off seq seq? seque sequence sequential? set set-validator! set? short short-array shorts shutdown-agents slurp some sort sort-by sorted-map sorted-map-by sorted-set sorted-set-by sorted? special-form-anchor special-symbol? split-at split-with str stream? string? struct struct-map subs subseq subvec supers swap! symbol symbol? sync syntax-symbol-anchor take take-last take-nth take-while test the-ns time to-array to-array-2d trampoline transient tree-seq true? type unchecked-add unchecked-dec unchecked-divide unchecked-inc unchecked-multiply unchecked-negate unchecked-remainder unchecked-subtract underive unquote unquote-splicing update-in update-proxy use val vals var-get var-set var? vary-meta vec vector vector? when when-first when-let when-not while with-bindings with-bindings* with-in-str with-loading-context with-local-vars with-meta with-open with-out-str with-precision xml-seq");
var indentKeys = makeKeywords(
// Built-ins
"ns fn def defn defmethod bound-fn if if-not case condp when while when-not when-first do future comment doto locking proxy with-open with-precision reify deftype defrecord defprotocol extend extend-protocol extend-type try catch " +
// Binding forms
"let letfn binding loop for doseq dotimes when-let if-let " +
// Data structures
"defstruct struct-map assoc " +
// clojure.test
"testing deftest " +
// contrib
"handler-case handle dotrace deftrace");
var tests = {
digit: /\d/,
digit_or_colon: /[\d:]/,
hex: /[0-9a-f]/i,
sign: /[+-]/,
exponent: /e/i,
keyword_char: /[^\s\(\[\;\)\]]/,
basic: /[\w\$_\-]/,
lang_keyword: /[\w*+!\-_?:\/]/
};
function stateStack(indent, type, prev) { // represents a state stack object
this.indent = indent;
this.type = type;
this.prev = prev;
}
function pushStack(state, indent, type) {
state.indentStack = new stateStack(indent, type, state.indentStack);
}
function popStack(state) {
state.indentStack = state.indentStack.prev;
}
function isNumber(ch, stream){
// hex
if ( ch === '0' && stream.eat(/x/i) ) {
stream.eatWhile(tests.hex);
return true;
}
// leading sign
if ( ( ch == '+' || ch == '-' ) && ( tests.digit.test(stream.peek()) ) ) {
stream.eat(tests.sign);
ch = stream.next();
}
if ( tests.digit.test(ch) ) {
stream.eat(ch);
stream.eatWhile(tests.digit);
if ( '.' == stream.peek() ) {
stream.eat('.');
stream.eatWhile(tests.digit);
}
if ( stream.eat(tests.exponent) ) {
stream.eat(tests.sign);
stream.eatWhile(tests.digit);
}
return true;
}
return false;
}
return {
startState: function () {
return {
indentStack: null,
indentation: 0,
mode: false
};
},
token: function (stream, state) {
if (state.indentStack == null && stream.sol()) {
// update indentation, but only if indentStack is empty
state.indentation = stream.indentation();
}
// skip spaces
if (stream.eatSpace()) {
return null;
}
var returnType = null;
switch(state.mode){
case "string": // multi-line string parsing mode
var next, escaped = false;
while ((next = stream.next()) != null) {
if (next == "\"" && !escaped) {
state.mode = false;
break;
}
escaped = !escaped && next == "\\";
}
returnType = STRING; // continue on in string mode
break;
default: // default parsing mode
var ch = stream.next();
if (ch == "\"") {
state.mode = "string";
returnType = STRING;
} else if (ch == "'" && !( tests.digit_or_colon.test(stream.peek()) )) {
returnType = ATOM;
} else if (ch == ";") { // comment
stream.skipToEnd(); // rest of the line is a comment
returnType = COMMENT;
} else if (isNumber(ch,stream)){
returnType = NUMBER;
} else if (ch == "(" || ch == "[") {
var keyWord = '', indentTemp = stream.column(), letter;
/**
Either
(indent-word ..
(non-indent-word ..
(;something else, bracket, etc.
*/
if (ch == "(") while ((letter = stream.eat(tests.keyword_char)) != null) {
keyWord += letter;
}
if (keyWord.length > 0 && (indentKeys.propertyIsEnumerable(keyWord) ||
/^(?:def|with)/.test(keyWord))) { // indent-word
pushStack(state, indentTemp + INDENT_WORD_SKIP, ch);
} else { // non-indent word
// we continue eating the spaces
stream.eatSpace();
if (stream.eol() || stream.peek() == ";") {
// nothing significant after
// we restart indentation 1 space after
pushStack(state, indentTemp + 1, ch);
} else {
pushStack(state, indentTemp + stream.current().length, ch); // else we match
}
}
stream.backUp(stream.current().length - 1); // undo all the eating
returnType = BRACKET;
} else if (ch == ")" || ch == "]") {
returnType = BRACKET;
if (state.indentStack != null && state.indentStack.type == (ch == ")" ? "(" : "[")) {
popStack(state);
}
} else if ( ch == ":" ) {
stream.eatWhile(tests.lang_keyword);
return ATOM;
} else {
stream.eatWhile(tests.basic);
if (keywords && keywords.propertyIsEnumerable(stream.current())) {
returnType = KEYWORD;
} else if (builtins && builtins.propertyIsEnumerable(stream.current())) {
returnType = BUILTIN;
} else if (atoms && atoms.propertyIsEnumerable(stream.current())) {
returnType = ATOM;
} else returnType = null;
}
}
return returnType;
},
indent: function (state, textAfter) {
if (state.indentStack == null) return state.indentation;
return state.indentStack.indent;
}
};
});
CodeMirror.defineMIME("text/x-clojure", "clojure");
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Clojure mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="clojure.js"></script>
<style>.CodeMirror {background: #f8f8f8;}</style>
<link rel="stylesheet" href="../../doc/docs.css">
</head>
<body>
<h1>CodeMirror: Clojure mode</h1>
<form><textarea id="code" name="code">
; Conway's Game of Life, based on the work of:
;; Laurent Petit https://gist.github.com/1200343
;; Christophe Grand http://clj-me.cgrand.net/2011/08/19/conways-game-of-life
(ns ^{:doc "Conway's Game of Life."}
game-of-life)
;; Core game of life's algorithm functions
(defn neighbours
"Given a cell's coordinates, returns the coordinates of its neighbours."
[[x y]]
(for [dx [-1 0 1] dy (if (zero? dx) [-1 1] [-1 0 1])]
[(+ dx x) (+ dy y)]))
(defn step
"Given a set of living cells, computes the new set of living cells."
[cells]
(set (for [[cell n] (frequencies (mapcat neighbours cells))
:when (or (= n 3) (and (= n 2) (cells cell)))]
cell)))
;; Utility methods for displaying game on a text terminal
(defn print-board
"Prints a board on *out*, representing a step in the game."
[board w h]
(doseq [x (range (inc w)) y (range (inc h))]
(if (= y 0) (print "\n"))
(print (if (board [x y]) "[X]" " . "))))
(defn display-grids
"Prints a squence of boards on *out*, representing several steps."
[grids w h]
(doseq [board grids]
(print-board board w h)
(print "\n")))
;; Launches an example board
(def
^{:doc "board represents the initial set of living cells"}
board #{[2 1] [2 2] [2 3]})
(display-grids (take 3 (iterate step board)) 5 5) </textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
</script>
<p><strong>MIME types defined:</strong> <code>text/x-clojure</code>.</p>
</body>
</html>
/**
* Link to the project's GitHub page:
* https://github.com/pickhardt/coffeescript-codemirror-mode
*/
CodeMirror.defineMode('coffeescript', function(conf) {
var ERRORCLASS = 'error';
function wordRegexp(words) {
return new RegExp("^((" + words.join(")|(") + "))\\b");
}
var singleOperators = new RegExp("^[\\+\\-\\*/%&|\\^~<>!\?]");
var singleDelimiters = new RegExp('^[\\(\\)\\[\\]\\{\\},:`=;\\.]');
var doubleOperators = new RegExp("^((\->)|(\=>)|(\\+\\+)|(\\+\\=)|(\\-\\-)|(\\-\\=)|(\\*\\*)|(\\*\\=)|(\\/\\/)|(\\/\\=)|(==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//))");
var doubleDelimiters = new RegExp("^((\\.\\.)|(\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))");
var tripleDelimiters = new RegExp("^((\\.\\.\\.)|(//=)|(>>=)|(<<=)|(\\*\\*=))");
var identifiers = new RegExp("^[_A-Za-z$][_A-Za-z$0-9]*");
var properties = new RegExp("^(@|this\.)[_A-Za-z$][_A-Za-z$0-9]*");
var wordOperators = wordRegexp(['and', 'or', 'not',
'is', 'isnt', 'in',
'instanceof', 'typeof']);
var indentKeywords = ['for', 'while', 'loop', 'if', 'unless', 'else',
'switch', 'try', 'catch', 'finally', 'class'];
var commonKeywords = ['break', 'by', 'continue', 'debugger', 'delete',
'do', 'in', 'of', 'new', 'return', 'then',
'this', 'throw', 'when', 'until'];
var keywords = wordRegexp(indentKeywords.concat(commonKeywords));
indentKeywords = wordRegexp(indentKeywords);
var stringPrefixes = new RegExp("^('{3}|\"{3}|['\"])");
var regexPrefixes = new RegExp("^(/{3}|/)");
var commonConstants = ['Infinity', 'NaN', 'undefined', 'null', 'true', 'false', 'on', 'off', 'yes', 'no'];
var constants = wordRegexp(commonConstants);
// Tokenizers
function tokenBase(stream, state) {
// Handle scope changes
if (stream.sol()) {
var scopeOffset = state.scopes[0].offset;
if (stream.eatSpace()) {
var lineOffset = stream.indentation();
if (lineOffset > scopeOffset) {
return 'indent';
} else if (lineOffset < scopeOffset) {
return 'dedent';
}
return null;
} else {
if (scopeOffset > 0) {
dedent(stream, state);
}
}
}
if (stream.eatSpace()) {
return null;
}
var ch = stream.peek();
// Handle docco title comment (single line)
if (stream.match("####")) {
stream.skipToEnd();
return 'comment';
}
// Handle multi line comments
if (stream.match("###")) {
state.tokenize = longComment;
return state.tokenize(stream, state);
}
// Single line comment
if (ch === '#') {
stream.skipToEnd();
return 'comment';
}
// Handle number literals
if (stream.match(/^-?[0-9\.]/, false)) {
var floatLiteral = false;
// Floats
if (stream.match(/^-?\d*\.\d+(e[\+\-]?\d+)?/i)) {
floatLiteral = true;
}
if (stream.match(/^-?\d+\.\d*/)) {
floatLiteral = true;
}
if (stream.match(/^-?\.\d+/)) {
floatLiteral = true;
}
if (floatLiteral) {
// prevent from getting extra . on 1..
if (stream.peek() == "."){
stream.backUp(1);
}
return 'number';
}
// Integers
var intLiteral = false;
// Hex
if (stream.match(/^-?0x[0-9a-f]+/i)) {
intLiteral = true;
}
// Decimal
if (stream.match(/^-?[1-9]\d*(e[\+\-]?\d+)?/)) {
intLiteral = true;
}
// Zero by itself with no other piece of number.
if (stream.match(/^-?0(?![\dx])/i)) {
intLiteral = true;
}
if (intLiteral) {
return 'number';
}
}
// Handle strings
if (stream.match(stringPrefixes)) {
state.tokenize = tokenFactory(stream.current(), 'string');
return state.tokenize(stream, state);
}
// Handle regex literals
if (stream.match(regexPrefixes)) {
if (stream.current() != '/' || stream.match(/^.*\//, false)) { // prevent highlight of division
state.tokenize = tokenFactory(stream.current(), 'string-2');
return state.tokenize(stream, state);
} else {
stream.backUp(1);
}
}
// Handle operators and delimiters
if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters)) {
return 'punctuation';
}
if (stream.match(doubleOperators)
|| stream.match(singleOperators)
|| stream.match(wordOperators)) {
return 'operator';
}
if (stream.match(singleDelimiters)) {
return 'punctuation';
}
if (stream.match(constants)) {
return 'atom';
}
if (stream.match(keywords)) {
return 'keyword';
}
if (stream.match(identifiers)) {
return 'variable';
}
if (stream.match(properties)) {
return 'property';
}
// Handle non-detected items
stream.next();
return ERRORCLASS;
}
function tokenFactory(delimiter, outclass) {
var singleline = delimiter.length == 1;
return function tokenString(stream, state) {
while (!stream.eol()) {
stream.eatWhile(/[^'"\/\\]/);
if (stream.eat('\\')) {
stream.next();
if (singleline && stream.eol()) {
return outclass;
}
} else if (stream.match(delimiter)) {
state.tokenize = tokenBase;
return outclass;
} else {
stream.eat(/['"\/]/);
}
}
if (singleline) {
if (conf.mode.singleLineStringErrors) {
outclass = ERRORCLASS;
} else {
state.tokenize = tokenBase;
}
}
return outclass;
};
}
function longComment(stream, state) {
while (!stream.eol()) {
stream.eatWhile(/[^#]/);
if (stream.match("###")) {
state.tokenize = tokenBase;
break;
}
stream.eatWhile("#");
}
return "comment";
}
function indent(stream, state, type) {
type = type || 'coffee';
var indentUnit = 0;
if (type === 'coffee') {
for (var i = 0; i < state.scopes.length; i++) {
if (state.scopes[i].type === 'coffee') {
indentUnit = state.scopes[i].offset + conf.indentUnit;
break;
}
}
} else {
indentUnit = stream.column() + stream.current().length;
}
state.scopes.unshift({
offset: indentUnit,
type: type
});
}
function dedent(stream, state) {
if (state.scopes.length == 1) return;
if (state.scopes[0].type === 'coffee') {
var _indent = stream.indentation();
var _indent_index = -1;
for (var i = 0; i < state.scopes.length; ++i) {
if (_indent === state.scopes[i].offset) {
_indent_index = i;
break;
}
}
if (_indent_index === -1) {
return true;
}
while (state.scopes[0].offset !== _indent) {
state.scopes.shift();
}
return false;
} else {
state.scopes.shift();
return false;
}
}
function tokenLexer(stream, state) {
var style = state.tokenize(stream, state);
var current = stream.current();
// Handle '.' connected identifiers
if (current === '.') {
style = state.tokenize(stream, state);
current = stream.current();
if (style === 'variable') {
return 'variable';
} else {
return ERRORCLASS;
}
}
// Handle scope changes.
if (current === 'return') {
state.dedent += 1;
}
if (((current === '->' || current === '=>') &&
!state.lambda &&
state.scopes[0].type == 'coffee' &&
stream.peek() === '')
|| style === 'indent') {
indent(stream, state);
}
var delimiter_index = '[({'.indexOf(current);
if (delimiter_index !== -1) {
indent(stream, state, '])}'.slice(delimiter_index, delimiter_index+1));
}
if (indentKeywords.exec(current)){
indent(stream, state);
}
if (current == 'then'){
dedent(stream, state);
}
if (style === 'dedent') {
if (dedent(stream, state)) {
return ERRORCLASS;
}
}
delimiter_index = '])}'.indexOf(current);
if (delimiter_index !== -1) {
if (dedent(stream, state)) {
return ERRORCLASS;
}
}
if (state.dedent > 0 && stream.eol() && state.scopes[0].type == 'coffee') {
if (state.scopes.length > 1) state.scopes.shift();
state.dedent -= 1;
}
return style;
}
var external = {
startState: function(basecolumn) {
return {
tokenize: tokenBase,
scopes: [{offset:basecolumn || 0, type:'coffee'}],
lastToken: null,
lambda: false,
dedent: 0
};
},
token: function(stream, state) {
var style = tokenLexer(stream, state);
state.lastToken = {style:style, content: stream.current()};
if (stream.eol() && stream.lambda) {
state.lambda = false;
}
return style;
},
indent: function(state, textAfter) {
if (state.tokenize != tokenBase) {
return 0;
}
return state.scopes[0].offset;
}
};
return external;
});
CodeMirror.defineMIME('text/x-coffeescript', 'coffeescript');
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: CoffeeScript mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="coffeescript.js"></script>
<style>.CodeMirror {border-top: 1px solid silver; border-bottom: 1px solid silver;}</style>
<link rel="stylesheet" href="../../doc/docs.css">
</head>
<body>
<h1>CodeMirror: CoffeeScript mode</h1>
<form><textarea id="code" name="code">
# CoffeeScript mode for CodeMirror
# Copyright (c) 2011 Jeff Pickhardt, released under
# the MIT License.
#
# Modified from the Python CodeMirror mode, which also is
# under the MIT License Copyright (c) 2010 Timothy Farrell.
#
# The following script, Underscore.coffee, is used to
# demonstrate CoffeeScript mode for CodeMirror.
#
# To download CoffeeScript mode for CodeMirror, go to:
# https://github.com/pickhardt/coffeescript-codemirror-mode
# **Underscore.coffee
# (c) 2011 Jeremy Ashkenas, DocumentCloud Inc.**
# Underscore is freely distributable under the terms of the
# [MIT license](http://en.wikipedia.org/wiki/MIT_License).
# Portions of Underscore are inspired by or borrowed from
# [Prototype.js](http://prototypejs.org/api), Oliver Steele's
# [Functional](http://osteele.com), and John Resig's
# [Micro-Templating](http://ejohn.org).
# For all details and documentation:
# http://documentcloud.github.com/underscore/
# Baseline setup
# --------------
# Establish the root object, `window` in the browser, or `global` on the server.
root = this
# Save the previous value of the `_` variable.
previousUnderscore = root._
### Multiline
comment
###
# Establish the object that gets thrown to break out of a loop iteration.
# `StopIteration` is SOP on Mozilla.
breaker = if typeof(StopIteration) is 'undefined' then '__break__' else StopIteration
#### Docco style single line comment (title)
# Helper function to escape **RegExp** contents, because JS doesn't have one.
escapeRegExp = (string) -> string.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1')
# Save bytes in the minified (but not gzipped) version:
ArrayProto = Array.prototype
ObjProto = Object.prototype
# Create quick reference variables for speed access to core prototypes.
slice = ArrayProto.slice
unshift = ArrayProto.unshift
toString = ObjProto.toString
hasOwnProperty = ObjProto.hasOwnProperty
propertyIsEnumerable = ObjProto.propertyIsEnumerable
# All **ECMA5** native implementations we hope to use are declared here.
nativeForEach = ArrayProto.forEach
nativeMap = ArrayProto.map
nativeReduce = ArrayProto.reduce
nativeReduceRight = ArrayProto.reduceRight
nativeFilter = ArrayProto.filter
nativeEvery = ArrayProto.every
nativeSome = ArrayProto.some
nativeIndexOf = ArrayProto.indexOf
nativeLastIndexOf = ArrayProto.lastIndexOf
nativeIsArray = Array.isArray
nativeKeys = Object.keys
# Create a safe reference to the Underscore object for use below.
_ = (obj) -> new wrapper(obj)
# Export the Underscore object for **CommonJS**.
if typeof(exports) != 'undefined' then exports._ = _
# Export Underscore to global scope.
root._ = _
# Current version.
_.VERSION = '1.1.0'
# Collection Functions
# --------------------
# The cornerstone, an **each** implementation.
# Handles objects implementing **forEach**, arrays, and raw objects.
_.each = (obj, iterator, context) ->
try
if nativeForEach and obj.forEach is nativeForEach
obj.forEach iterator, context
else if _.isNumber obj.length
iterator.call context, obj[i], i, obj for i in [0...obj.length]
else
iterator.call context, val, key, obj for own key, val of obj
catch e
throw e if e isnt breaker
obj
# Return the results of applying the iterator to each element. Use JavaScript
# 1.6's version of **map**, if possible.
_.map = (obj, iterator, context) ->
return obj.map(iterator, context) if nativeMap and obj.map is nativeMap
results = []
_.each obj, (value, index, list) ->
results.push iterator.call context, value, index, list
results
# **Reduce** builds up a single result from a list of values. Also known as
# **inject**, or **foldl**. Uses JavaScript 1.8's version of **reduce**, if possible.
_.reduce = (obj, iterator, memo, context) ->
if nativeReduce and obj.reduce is nativeReduce
iterator = _.bind iterator, context if context
return obj.reduce iterator, memo
_.each obj, (value, index, list) ->
memo = iterator.call context, memo, value, index, list
memo
# The right-associative version of **reduce**, also known as **foldr**. Uses
# JavaScript 1.8's version of **reduceRight**, if available.
_.reduceRight = (obj, iterator, memo, context) ->
if nativeReduceRight and obj.reduceRight is nativeReduceRight
iterator = _.bind iterator, context if context
return obj.reduceRight iterator, memo
reversed = _.clone(_.toArray(obj)).reverse()
_.reduce reversed, iterator, memo, context
# Return the first value which passes a truth test.
_.detect = (obj, iterator, context) ->
result = null
_.each obj, (value, index, list) ->
if iterator.call context, value, index, list
result = value
_.breakLoop()
result
# Return all the elements that pass a truth test. Use JavaScript 1.6's
# **filter**, if it exists.
_.filter = (obj, iterator, context) ->
return obj.filter iterator, context if nativeFilter and obj.filter is nativeFilter
results = []
_.each obj, (value, index, list) ->
results.push value if iterator.call context, value, index, list
results
# Return all the elements for which a truth test fails.
_.reject = (obj, iterator, context) ->
results = []
_.each obj, (value, index, list) ->
results.push value if not iterator.call context, value, index, list
results
# Determine whether all of the elements match a truth test. Delegate to
# JavaScript 1.6's **every**, if it is present.
_.every = (obj, iterator, context) ->
iterator ||= _.identity
return obj.every iterator, context if nativeEvery and obj.every is nativeEvery
result = true
_.each obj, (value, index, list) ->
_.breakLoop() unless (result = result and iterator.call(context, value, index, list))
result
# Determine if at least one element in the object matches a truth test. Use
# JavaScript 1.6's **some**, if it exists.
_.some = (obj, iterator, context) ->
iterator ||= _.identity
return obj.some iterator, context if nativeSome and obj.some is nativeSome
result = false
_.each obj, (value, index, list) ->
_.breakLoop() if (result = iterator.call(context, value, index, list))
result
# Determine if a given value is included in the array or object,
# based on `===`.
_.include = (obj, target) ->
return _.indexOf(obj, target) isnt -1 if nativeIndexOf and obj.indexOf is nativeIndexOf
return true for own key, val of obj when val is target
false
# Invoke a method with arguments on every item in a collection.
_.invoke = (obj, method) ->
args = _.rest arguments, 2
(if method then val[method] else val).apply(val, args) for val in obj
# Convenience version of a common use case of **map**: fetching a property.
_.pluck = (obj, key) ->
_.map(obj, (val) -> val[key])
# Return the maximum item or (item-based computation).
_.max = (obj, iterator, context) ->
return Math.max.apply(Math, obj) if not iterator and _.isArray(obj)
result = computed: -Infinity
_.each obj, (value, index, list) ->
computed = if iterator then iterator.call(context, value, index, list) else value
computed >= result.computed and (result = {value: value, computed: computed})
result.value
# Return the minimum element (or element-based computation).
_.min = (obj, iterator, context) ->
return Math.min.apply(Math, obj) if not iterator and _.isArray(obj)
result = computed: Infinity
_.each obj, (value, index, list) ->
computed = if iterator then iterator.call(context, value, index, list) else value
computed < result.computed and (result = {value: value, computed: computed})
result.value
# Sort the object's values by a criterion produced by an iterator.
_.sortBy = (obj, iterator, context) ->
_.pluck(((_.map obj, (value, index, list) ->
{value: value, criteria: iterator.call(context, value, index, list)}
).sort((left, right) ->
a = left.criteria; b = right.criteria
if a < b then -1 else if a > b then 1 else 0
)), 'value')
# Use a comparator function to figure out at what index an object should
# be inserted so as to maintain order. Uses binary search.
_.sortedIndex = (array, obj, iterator) ->
iterator ||= _.identity
low = 0
high = array.length
while low < high
mid = (low + high) >> 1
if iterator(array[mid]) < iterator(obj) then low = mid + 1 else high = mid
low
# Convert anything iterable into a real, live array.
_.toArray = (iterable) ->
return [] if (!iterable)
return iterable.toArray() if (iterable.toArray)
return iterable if (_.isArray(iterable))
return slice.call(iterable) if (_.isArguments(iterable))
_.values(iterable)
# Return the number of elements in an object.
_.size = (obj) -> _.toArray(obj).length
# Array Functions
# ---------------
# Get the first element of an array. Passing `n` will return the first N
# values in the array. Aliased as **head**. The `guard` check allows it to work
# with **map**.
_.first = (array, n, guard) ->
if n and not guard then slice.call(array, 0, n) else array[0]
# Returns everything but the first entry of the array. Aliased as **tail**.
# Especially useful on the arguments object. Passing an `index` will return
# the rest of the values in the array from that index onward. The `guard`
# check allows it to work with **map**.
_.rest = (array, index, guard) ->
slice.call(array, if _.isUndefined(index) or guard then 1 else index)
# Get the last element of an array.
_.last = (array) -> array[array.length - 1]
# Trim out all falsy values from an array.
_.compact = (array) -> item for item in array when item
# Return a completely flattened version of an array.
_.flatten = (array) ->
_.reduce array, (memo, value) ->
return memo.concat(_.flatten(value)) if _.isArray value
memo.push value
memo
, []
# Return a version of the array that does not contain the specified value(s).
_.without = (array) ->
values = _.rest arguments
val for val in _.toArray(array) when not _.include values, val
# Produce a duplicate-free version of the array. If the array has already
# been sorted, you have the option of using a faster algorithm.
_.uniq = (array, isSorted) ->
memo = []
for el, i in _.toArray array
memo.push el if i is 0 || (if isSorted is true then _.last(memo) isnt el else not _.include(memo, el))
memo
# Produce an array that contains every item shared between all the
# passed-in arrays.
_.intersect = (array) ->
rest = _.rest arguments
_.select _.uniq(array), (item) ->
_.all rest, (other) ->
_.indexOf(other, item) >= 0
# Zip together multiple lists into a single array -- elements that share
# an index go together.
_.zip = ->
length = _.max _.pluck arguments, 'length'
results = new Array length
for i in [0...length]
results[i] = _.pluck arguments, String i
results
# If the browser doesn't supply us with **indexOf** (I'm looking at you, MSIE),
# we need this function. Return the position of the first occurrence of an
# item in an array, or -1 if the item is not included in the array.
_.indexOf = (array, item) ->
return array.indexOf item if nativeIndexOf and array.indexOf is nativeIndexOf
i = 0; l = array.length
while l - i
if array[i] is item then return i else i++
-1
# Provide JavaScript 1.6's **lastIndexOf**, delegating to the native function,
# if possible.
_.lastIndexOf = (array, item) ->
return array.lastIndexOf(item) if nativeLastIndexOf and array.lastIndexOf is nativeLastIndexOf
i = array.length
while i
if array[i] is item then return i else i--
-1
# Generate an integer Array containing an arithmetic progression. A port of
# [the native Python **range** function](http://docs.python.org/library/functions.html#range).
_.range = (start, stop, step) ->
a = arguments
solo = a.length <= 1
i = start = if solo then 0 else a[0]
stop = if solo then a[0] else a[1]
step = a[2] or 1
len = Math.ceil((stop - start) / step)
return [] if len <= 0
range = new Array len
idx = 0
loop
return range if (if step > 0 then i - stop else stop - i) >= 0
range[idx] = i
idx++
i+= step
# Function Functions
# ------------------
# Create a function bound to a given object (assigning `this`, and arguments,
# optionally). Binding with arguments is also known as **curry**.
_.bind = (func, obj) ->
args = _.rest arguments, 2
-> func.apply obj or root, args.concat arguments
# Bind all of an object's methods to that object. Useful for ensuring that
# all callbacks defined on an object belong to it.
_.bindAll = (obj) ->
funcs = if arguments.length > 1 then _.rest(arguments) else _.functions(obj)
_.each funcs, (f) -> obj[f] = _.bind obj[f], obj
obj
# Delays a function for the given number of milliseconds, and then calls
# it with the arguments supplied.
_.delay = (func, wait) ->
args = _.rest arguments, 2
setTimeout((-> func.apply(func, args)), wait)
# Memoize an expensive function by storing its results.
_.memoize = (func, hasher) ->
memo = {}
hasher or= _.identity
->
key = hasher.apply this, arguments
return memo[key] if key of memo
memo[key] = func.apply this, arguments
# Defers a function, scheduling it to run after the current call stack has
# cleared.
_.defer = (func) ->
_.delay.apply _, [func, 1].concat _.rest arguments
# Returns the first function passed as an argument to the second,
# allowing you to adjust arguments, run code before and after, and
# conditionally execute the original function.
_.wrap = (func, wrapper) ->
-> wrapper.apply wrapper, [func].concat arguments
# Returns a function that is the composition of a list of functions, each
# consuming the return value of the function that follows.
_.compose = ->
funcs = arguments
->
args = arguments
for i in [funcs.length - 1..0] by -1
args = [funcs[i].apply(this, args)]
args[0]
# Object Functions
# ----------------
# Retrieve the names of an object's properties.
_.keys = nativeKeys or (obj) ->
return _.range 0, obj.length if _.isArray(obj)
key for key, val of obj
# Retrieve the values of an object's properties.
_.values = (obj) ->
_.map obj, _.identity
# Return a sorted list of the function names available in Underscore.
_.functions = (obj) ->
_.filter(_.keys(obj), (key) -> _.isFunction(obj[key])).sort()
# Extend a given object with all of the properties in a source object.
_.extend = (obj) ->
for source in _.rest(arguments)
obj[key] = val for key, val of source
obj
# Create a (shallow-cloned) duplicate of an object.
_.clone = (obj) ->
return obj.slice 0 if _.isArray obj
_.extend {}, obj
# Invokes interceptor with the obj, and then returns obj.
# The primary purpose of this method is to "tap into" a method chain,
# in order to perform operations on intermediate results within
the chain.
_.tap = (obj, interceptor) ->
interceptor obj
obj
# Perform a deep comparison to check if two objects are equal.
_.isEqual = (a, b) ->
# Check object identity.
return true if a is b
# Different types?
atype = typeof(a); btype = typeof(b)
return false if atype isnt btype
# Basic equality test (watch out for coercions).
return true if `a == b`
# One is falsy and the other truthy.
return false if (!a and b) or (a and !b)
# One of them implements an `isEqual()`?
return a.isEqual(b) if a.isEqual
# Check dates' integer values.
return a.getTime() is b.getTime() if _.isDate(a) and _.isDate(b)
# Both are NaN?
return false if _.isNaN(a) and _.isNaN(b)
# Compare regular expressions.
if _.isRegExp(a) and _.isRegExp(b)
return a.source is b.source and
a.global is b.global and
a.ignoreCase is b.ignoreCase and
a.multiline is b.multiline
# If a is not an object by this point, we can't handle it.
return false if atype isnt 'object'
# Check for different array lengths before comparing contents.
return false if a.length and (a.length isnt b.length)
# Nothing else worked, deep compare the contents.
aKeys = _.keys(a); bKeys = _.keys(b)
# Different object sizes?
return false if aKeys.length isnt bKeys.length
# Recursive comparison of contents.
return false for key, val of a when !(key of b) or !_.isEqual(val, b[key])
true
# Is a given array or object empty?
_.isEmpty = (obj) ->
return obj.length is 0 if _.isArray(obj) or _.isString(obj)
return false for own key of obj
true
# Is a given value a DOM element?
_.isElement = (obj) -> obj and obj.nodeType is 1
# Is a given value an array?
_.isArray = nativeIsArray or (obj) -> !!(obj and obj.concat and obj.unshift and not obj.callee)
# Is a given variable an arguments object?
_.isArguments = (obj) -> obj and obj.callee
# Is the given value a function?
_.isFunction = (obj) -> !!(obj and obj.constructor and obj.call and obj.apply)
# Is the given value a string?
_.isString = (obj) -> !!(obj is '' or (obj and obj.charCodeAt and obj.substr))
# Is a given value a number?
_.isNumber = (obj) -> (obj is +obj) or toString.call(obj) is '[object Number]'
# Is a given value a boolean?
_.isBoolean = (obj) -> obj is true or obj is false
# Is a given value a Date?
_.isDate = (obj) -> !!(obj and obj.getTimezoneOffset and obj.setUTCFullYear)
# Is the given value a regular expression?
_.isRegExp = (obj) -> !!(obj and obj.exec and (obj.ignoreCase or obj.ignoreCase is false))
# Is the given value NaN -- this one is interesting. `NaN != NaN`, and
# `isNaN(undefined) == true`, so we make sure it's a number first.
_.isNaN = (obj) -> _.isNumber(obj) and window.isNaN(obj)
# Is a given value equal to null?
_.isNull = (obj) -> obj is null
# Is a given variable undefined?
_.isUndefined = (obj) -> typeof obj is 'undefined'
# Utility Functions
# -----------------
# Run Underscore.js in noConflict mode, returning the `_` variable to its
# previous owner. Returns a reference to the Underscore object.
_.noConflict = ->
root._ = previousUnderscore
this
# Keep the identity function around for default iterators.
_.identity = (value) -> value
# Run a function `n` times.
_.times = (n, iterator, context) ->
iterator.call context, i for i in [0...n]
# Break out of the middle of an iteration.
_.breakLoop = -> throw breaker
# Add your own custom functions to the Underscore object, ensuring that
# they're correctly added to the OOP wrapper as well.
_.mixin = (obj) ->
for name in _.functions(obj)
addToWrapper name, _[name] = obj[name]
# Generate a unique integer id (unique within the entire client session).
# Useful for temporary DOM ids.
idCounter = 0
_.uniqueId = (prefix) ->
(prefix or '') + idCounter++
# By default, Underscore uses **ERB**-style template delimiters, change the
# following template settings to use alternative delimiters.
_.templateSettings = {
start: '<%'
end: '%>'
interpolate: /<%=(.+?)%>/g
}
# JavaScript templating a-la **ERB**, pilfered from John Resig's
# *Secrets of the JavaScript Ninja*, page 83.
# Single-quote fix from Rick Strahl.
# With alterations for arbitrary delimiters, and to preserve whitespace.
_.template = (str, data) ->
c = _.templateSettings
endMatch = new RegExp("'(?=[^"+c.end.substr(0, 1)+"]*"+escapeRegExp(c.end)+")","g")
fn = new Function 'obj',
'var p=[],print=function(){p.push.apply(p,arguments);};' +
'with(obj||{}){p.push(\'' +
str.replace(/\r/g, '\\r')
.replace(/\n/g, '\\n')
.replace(/\t/g, '\\t')
.replace(endMatch,"���")
.split("'").join("\\'")
.split("���").join("'")
.replace(c.interpolate, "',$1,'")
.split(c.start).join("');")
.split(c.end).join("p.push('") +
"');}return p.join('');"
if data then fn(data) else fn
# Aliases
# -------
_.forEach = _.each
_.foldl = _.inject = _.reduce
_.foldr = _.reduceRight
_.select = _.filter
_.all = _.every
_.any = _.some
_.contains = _.include
_.head = _.first
_.tail = _.rest
_.methods = _.functions
# Setup the OOP Wrapper
# ---------------------
# If Underscore is called as a function, it returns a wrapped object that
# can be used OO-style. This wrapper holds altered versions of all the
# underscore functions. Wrapped objects may be chained.
wrapper = (obj) ->
this._wrapped = obj
this
# Helper function to continue chaining intermediate results.
result = (obj, chain) ->
if chain then _(obj).chain() else obj
# A method to easily add functions to the OOP wrapper.
addToWrapper = (name, func) ->
wrapper.prototype[name] = ->
args = _.toArray arguments
unshift.call args, this._wrapped
result func.apply(_, args), this._chain
# Add all ofthe Underscore functions to the wrapper object.
_.mixin _
# Add all mutator Array functions to the wrapper.
_.each ['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], (name) ->
method = Array.prototype[name]
wrapper.prototype[name] = ->
method.apply(this._wrapped, arguments)
result(this._wrapped, this._chain)
# Add all accessor Array functions to the wrapper.
_.each ['concat', 'join', 'slice'], (name) ->
method = Array.prototype[name]
wrapper.prototype[name] = ->
result(method.apply(this._wrapped, arguments), this._chain)
# Start chaining a wrapped Underscore object.
wrapper::chain = ->
this._chain = true
this
# Extracts the result from a wrapped and chained object.
wrapper::value = -> this._wrapped
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
</script>
<p><strong>MIME types defined:</strong> <code>text/x-coffeescript</code>.</p>
<p>The CoffeeScript mode was written by Jeff Pickhardt (<a href="LICENSE">license</a>).</p>
</body>
</html>
The MIT License
Copyright (c) 2011 Jeff Pickhardt
Modified from the Python CodeMirror mode, Copyright (c) 2010 Timothy Farrell
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
CodeMirror.defineMode("commonlisp", function (config) {
var assumeBody = /^with|^def|^do|^prog|case$|^cond$|bind$|when$|unless$/;
var numLiteral = /^(?:[+\-]?(?:\d+|\d*\.\d+)(?:[efd][+\-]?\d+)?|[+\-]?\d+(?:\/[+\-]?\d+)?|#b[+\-]?[01]+|#o[+\-]?[0-7]+|#x[+\-]?[\da-f]+)/;
var symbol = /[^\s'`,@()\[\]";]/;
var type;
function readSym(stream) {
var ch;
while (ch = stream.next()) {
if (ch == "\\") stream.next();
else if (!symbol.test(ch)) { stream.backUp(1); break; }
}
return stream.current();
}
function base(stream, state) {
if (stream.eatSpace()) {type = "ws"; return null;}
if (stream.match(numLiteral)) return "number";
var ch = stream.next();
if (ch == "\\") ch = stream.next();
if (ch == '"') return (state.tokenize = inString)(stream, state);
else if (ch == "(") { type = "open"; return "bracket"; }
else if (ch == ")" || ch == "]") { type = "close"; return "bracket"; }
else if (ch == ";") { stream.skipToEnd(); type = "ws"; return "comment"; }
else if (/['`,@]/.test(ch)) return null;
else if (ch == "|") {
if (stream.skipTo("|")) { stream.next(); return "symbol"; }
else { stream.skipToEnd(); return "error"; }
} else if (ch == "#") {
var ch = stream.next();
if (ch == "[") { type = "open"; return "bracket"; }
else if (/[+\-=\.']/.test(ch)) return null;
else if (/\d/.test(ch) && stream.match(/^\d*#/)) return null;
else if (ch == "|") return (state.tokenize = inComment)(stream, state);
else if (ch == ":") { readSym(stream); return "meta"; }
else return "error";
} else {
var name = readSym(stream);
if (name == ".") return null;
type = "symbol";
if (name == "nil" || name == "t") return "atom";
if (name.charAt(0) == ":") return "keyword";
if (name.charAt(0) == "&") return "variable-2";
return "variable";
}
}
function inString(stream, state) {
var escaped = false, next;
while (next = stream.next()) {
if (next == '"' && !escaped) { state.tokenize = base; break; }
escaped = !escaped && next == "\\";
}
return "string";
}
function inComment(stream, state) {
var next, last;
while (next = stream.next()) {
if (next == "#" && last == "|") { state.tokenize = base; break; }
last = next;
}
type = "ws";
return "comment";
}
return {
startState: function () {
return {ctx: {prev: null, start: 0, indentTo: 0}, tokenize: base};
},
token: function (stream, state) {
if (stream.sol() && typeof state.ctx.indentTo != "number")
state.ctx.indentTo = state.ctx.start + 1;
type = null;
var style = state.tokenize(stream, state);
if (type != "ws") {
if (state.ctx.indentTo == null) {
if (type == "symbol" && assumeBody.test(stream.current()))
state.ctx.indentTo = state.ctx.start + config.indentUnit;
else
state.ctx.indentTo = "next";
} else if (state.ctx.indentTo == "next") {
state.ctx.indentTo = stream.column();
}
}
if (type == "open") state.ctx = {prev: state.ctx, start: stream.column(), indentTo: null};
else if (type == "close") state.ctx = state.ctx.prev || state.ctx;
return style;
},
indent: function (state, textAfter) {
var i = state.ctx.indentTo;
return typeof i == "number" ? i : state.ctx.start + 1;
}
};
});
CodeMirror.defineMIME("text/x-common-lisp", "commonlisp");
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Common Lisp mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="commonlisp.js"></script>
<style>.CodeMirror {background: #f8f8f8;}</style>
<link rel="stylesheet" href="../../doc/docs.css">
</head>
<body>
<h1>CodeMirror: Common Lisp mode</h1>
<form><textarea id="code" name="code">(in-package :cl-postgres)
;; These are used to synthesize reader and writer names for integer
;; reading/writing functions when the amount of bytes and the
;; signedness is known. Both the macro that creates the functions and
;; some macros that use them create names this way.
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun integer-reader-name (bytes signed)
(intern (with-standard-io-syntax
(format nil "~a~a~a~a" '#:read- (if signed "" '#:u) '#:int bytes))))
(defun integer-writer-name (bytes signed)
(intern (with-standard-io-syntax
(format nil "~a~a~a~a" '#:write- (if signed "" '#:u) '#:int bytes)))))
(defmacro integer-reader (bytes)
"Create a function to read integers from a binary stream."
(let ((bits (* bytes 8)))
(labels ((return-form (signed)
(if signed
`(if (logbitp ,(1- bits) result)
(dpb result (byte ,(1- bits) 0) -1)
result)
`result))
(generate-reader (signed)
`(defun ,(integer-reader-name bytes signed) (socket)
(declare (type stream socket)
#.*optimize*)
,(if (= bytes 1)
`(let ((result (the (unsigned-byte 8) (read-byte socket))))
(declare (type (unsigned-byte 8) result))
,(return-form signed))
`(let ((result 0))
(declare (type (unsigned-byte ,bits) result))
,@(loop :for byte :from (1- bytes) :downto 0
:collect `(setf (ldb (byte 8 ,(* 8 byte)) result)
(the (unsigned-byte 8) (read-byte socket))))
,(return-form signed))))))
`(progn
;; This causes weird errors on SBCL in some circumstances. Disabled for now.
;; (declaim (inline ,(integer-reader-name bytes t)
;; ,(integer-reader-name bytes nil)))
(declaim (ftype (function (t) (signed-byte ,bits))
,(integer-reader-name bytes t)))
,(generate-reader t)
(declaim (ftype (function (t) (unsigned-byte ,bits))
,(integer-reader-name bytes nil)))
,(generate-reader nil)))))
(defmacro integer-writer (bytes)
"Create a function to write integers to a binary stream."
(let ((bits (* 8 bytes)))
`(progn
(declaim (inline ,(integer-writer-name bytes t)
,(integer-writer-name bytes nil)))
(defun ,(integer-writer-name bytes nil) (socket value)
(declare (type stream socket)
(type (unsigned-byte ,bits) value)
#.*optimize*)
,@(if (= bytes 1)
`((write-byte value socket))
(loop :for byte :from (1- bytes) :downto 0
:collect `(write-byte (ldb (byte 8 ,(* byte 8)) value)
socket)))
(values))
(defun ,(integer-writer-name bytes t) (socket value)
(declare (type stream socket)
(type (signed-byte ,bits) value)
#.*optimize*)
,@(if (= bytes 1)
`((write-byte (ldb (byte 8 0) value) socket))
(loop :for byte :from (1- bytes) :downto 0
:collect `(write-byte (ldb (byte 8 ,(* byte 8)) value)
socket)))
(values)))))
;; All the instances of the above that we need.
(integer-reader 1)
(integer-reader 2)
(integer-reader 4)
(integer-reader 8)
(integer-writer 1)
(integer-writer 2)
(integer-writer 4)
(defun write-bytes (socket bytes)
"Write a byte-array to a stream."
(declare (type stream socket)
(type (simple-array (unsigned-byte 8)) bytes)
#.*optimize*)
(write-sequence bytes socket))
(defun write-str (socket string)
"Write a null-terminated string to a stream \(encoding it when UTF-8
support is enabled.)."
(declare (type stream socket)
(type string string)
#.*optimize*)
(enc-write-string string socket)
(write-uint1 socket 0))
(declaim (ftype (function (t unsigned-byte)
(simple-array (unsigned-byte 8) (*)))
read-bytes))
(defun read-bytes (socket length)
"Read a byte array of the given length from a stream."
(declare (type stream socket)
(type fixnum length)
#.*optimize*)
(let ((result (make-array length :element-type '(unsigned-byte 8))))
(read-sequence result socket)
result))
(declaim (ftype (function (t) string) read-str))
(defun read-str (socket)
"Read a null-terminated string from a stream. Takes care of encoding
when UTF-8 support is enabled."
(declare (type stream socket)
#.*optimize*)
(enc-read-string socket :null-terminated t))
(defun skip-bytes (socket length)
"Skip a given number of bytes in a binary stream."
(declare (type stream socket)
(type (unsigned-byte 32) length)
#.*optimize*)
(dotimes (i length)
(read-byte socket)))
(defun skip-str (socket)
"Skip a null-terminated string."
(declare (type stream socket)
#.*optimize*)
(loop :for char :of-type fixnum = (read-byte socket)
:until (zerop char)))
(defun ensure-socket-is-closed (socket &amp;key abort)
(when (open-stream-p socket)
(handler-case
(close socket :abort abort)
(error (error)
(warn "Ignoring the error which happened while trying to close PostgreSQL socket: ~A" error)))))
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {lineNumbers: true});
</script>
<p><strong>MIME types defined:</strong> <code>text/x-common-lisp</code>.</p>
</body>
</html>
CodeMirror.defineMode("css", function(config) {
var indentUnit = config.indentUnit, type;
var atMediaTypes = keySet([
"all", "aural", "braille", "handheld", "print", "projection", "screen",
"tty", "tv", "embossed"
]);
var atMediaFeatures = keySet([
"width", "min-width", "max-width", "height", "min-height", "max-height",
"device-width", "min-device-width", "max-device-width", "device-height",
"min-device-height", "max-device-height", "aspect-ratio",
"min-aspect-ratio", "max-aspect-ratio", "device-aspect-ratio",
"min-device-aspect-ratio", "max-device-aspect-ratio", "color", "min-color",
"max-color", "color-index", "min-color-index", "max-color-index",
"monochrome", "min-monochrome", "max-monochrome", "resolution",
"min-resolution", "max-resolution", "scan", "grid"
]);
var propertyKeywords = keySet([
"align-content", "align-items", "align-self", "alignment-adjust",
"alignment-baseline", "anchor-point", "animation", "animation-delay",
"animation-direction", "animation-duration", "animation-iteration-count",
"animation-name", "animation-play-state", "animation-timing-function",
"appearance", "azimuth", "backface-visibility", "background",
"background-attachment", "background-clip", "background-color",
"background-image", "background-origin", "background-position",
"background-repeat", "background-size", "baseline-shift", "binding",
"bleed", "bookmark-label", "bookmark-level", "bookmark-state",
"bookmark-target", "border", "border-bottom", "border-bottom-color",
"border-bottom-left-radius", "border-bottom-right-radius",
"border-bottom-style", "border-bottom-width", "border-collapse",
"border-color", "border-image", "border-image-outset",
"border-image-repeat", "border-image-slice", "border-image-source",
"border-image-width", "border-left", "border-left-color",
"border-left-style", "border-left-width", "border-radius", "border-right",
"border-right-color", "border-right-style", "border-right-width",
"border-spacing", "border-style", "border-top", "border-top-color",
"border-top-left-radius", "border-top-right-radius", "border-top-style",
"border-top-width", "border-width", "bottom", "box-decoration-break",
"box-shadow", "box-sizing", "break-after", "break-before", "break-inside",
"caption-side", "clear", "clip", "color", "color-profile", "column-count",
"column-fill", "column-gap", "column-rule", "column-rule-color",
"column-rule-style", "column-rule-width", "column-span", "column-width",
"columns", "content", "counter-increment", "counter-reset", "crop", "cue",
"cue-after", "cue-before", "cursor", "direction", "display",
"dominant-baseline", "drop-initial-after-adjust",
"drop-initial-after-align", "drop-initial-before-adjust",
"drop-initial-before-align", "drop-initial-size", "drop-initial-value",
"elevation", "empty-cells", "fit", "fit-position", "flex", "flex-basis",
"flex-direction", "flex-flow", "flex-grow", "flex-shrink", "flex-wrap",
"float", "float-offset", "font", "font-feature-settings", "font-family",
"font-kerning", "font-language-override", "font-size", "font-size-adjust",
"font-stretch", "font-style", "font-synthesis", "font-variant",
"font-variant-alternates", "font-variant-caps", "font-variant-east-asian",
"font-variant-ligatures", "font-variant-numeric", "font-variant-position",
"font-weight", "grid-cell", "grid-column", "grid-column-align",
"grid-column-sizing", "grid-column-span", "grid-columns", "grid-flow",
"grid-row", "grid-row-align", "grid-row-sizing", "grid-row-span",
"grid-rows", "grid-template", "hanging-punctuation", "height", "hyphens",
"icon", "image-orientation", "image-rendering", "image-resolution",
"inline-box-align", "justify-content", "left", "letter-spacing",
"line-break", "line-height", "line-stacking", "line-stacking-ruby",
"line-stacking-shift", "line-stacking-strategy", "list-style",
"list-style-image", "list-style-position", "list-style-type", "margin",
"margin-bottom", "margin-left", "margin-right", "margin-top",
"marker-offset", "marks", "marquee-direction", "marquee-loop",
"marquee-play-count", "marquee-speed", "marquee-style", "max-height",
"max-width", "min-height", "min-width", "move-to", "nav-down", "nav-index",
"nav-left", "nav-right", "nav-up", "opacity", "order", "orphans", "outline",
"outline-color", "outline-offset", "outline-style", "outline-width",
"overflow", "overflow-style", "overflow-wrap", "overflow-x", "overflow-y",
"padding", "padding-bottom", "padding-left", "padding-right", "padding-top",
"page", "page-break-after", "page-break-before", "page-break-inside",
"page-policy", "pause", "pause-after", "pause-before", "perspective",
"perspective-origin", "pitch", "pitch-range", "play-during", "position",
"presentation-level", "punctuation-trim", "quotes", "rendering-intent",
"resize", "rest", "rest-after", "rest-before", "richness", "right",
"rotation", "rotation-point", "ruby-align", "ruby-overhang",
"ruby-position", "ruby-span", "size", "speak", "speak-as", "speak-header",
"speak-numeral", "speak-punctuation", "speech-rate", "stress", "string-set",
"tab-size", "table-layout", "target", "target-name", "target-new",
"target-position", "text-align", "text-align-last", "text-decoration",
"text-decoration-color", "text-decoration-line", "text-decoration-skip",
"text-decoration-style", "text-emphasis", "text-emphasis-color",
"text-emphasis-position", "text-emphasis-style", "text-height",
"text-indent", "text-justify", "text-outline", "text-shadow",
"text-space-collapse", "text-transform", "text-underline-position",
"text-wrap", "top", "transform", "transform-origin", "transform-style",
"transition", "transition-delay", "transition-duration",
"transition-property", "transition-timing-function", "unicode-bidi",
"vertical-align", "visibility", "voice-balance", "voice-duration",
"voice-family", "voice-pitch", "voice-range", "voice-rate", "voice-stress",
"voice-volume", "volume", "white-space", "widows", "width", "word-break",
"word-spacing", "word-wrap", "z-index"
]);
var colorKeywords = keySet([
"black", "silver", "gray", "white", "maroon", "red", "purple", "fuchsia",
"green", "lime", "olive", "yellow", "navy", "blue", "teal", "aqua"
]);
var valueKeywords = keySet([
"above", "absolute", "activeborder", "activecaption", "afar",
"after-white-space", "ahead", "alias", "all", "all-scroll", "alternate",
"always", "amharic", "amharic-abegede", "antialiased", "appworkspace",
"arabic-indic", "armenian", "asterisks", "auto", "avoid", "background",
"backwards", "baseline", "below", "bidi-override", "binary", "bengali",
"blink", "block", "block-axis", "bold", "bolder", "border", "border-box",
"both", "bottom", "break-all", "break-word", "button", "button-bevel",
"buttonface", "buttonhighlight", "buttonshadow", "buttontext", "cambodian",
"capitalize", "caps-lock-indicator", "caption", "captiontext", "caret",
"cell", "center", "checkbox", "circle", "cjk-earthly-branch",
"cjk-heavenly-stem", "cjk-ideographic", "clear", "clip", "close-quote",
"col-resize", "collapse", "compact", "condensed", "contain", "content",
"content-box", "context-menu", "continuous", "copy", "cover", "crop",
"cross", "crosshair", "currentcolor", "cursive", "dashed", "decimal",
"decimal-leading-zero", "default", "default-button", "destination-atop",
"destination-in", "destination-out", "destination-over", "devanagari",
"disc", "discard", "document", "dot-dash", "dot-dot-dash", "dotted",
"double", "down", "e-resize", "ease", "ease-in", "ease-in-out", "ease-out",
"element", "ellipsis", "embed", "end", "ethiopic", "ethiopic-abegede",
"ethiopic-abegede-am-et", "ethiopic-abegede-gez", "ethiopic-abegede-ti-er",
"ethiopic-abegede-ti-et", "ethiopic-halehame-aa-er",
"ethiopic-halehame-aa-et", "ethiopic-halehame-am-et",
"ethiopic-halehame-gez", "ethiopic-halehame-om-et",
"ethiopic-halehame-sid-et", "ethiopic-halehame-so-et",
"ethiopic-halehame-ti-er", "ethiopic-halehame-ti-et",
"ethiopic-halehame-tig", "ew-resize", "expanded", "extra-condensed",
"extra-expanded", "fantasy", "fast", "fill", "fixed", "flat", "footnotes",
"forwards", "from", "geometricPrecision", "georgian", "graytext", "groove",
"gujarati", "gurmukhi", "hand", "hangul", "hangul-consonant", "hebrew",
"help", "hidden", "hide", "higher", "highlight", "highlighttext",
"hiragana", "hiragana-iroha", "horizontal", "hsl", "hsla", "icon", "ignore",
"inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite",
"infobackground", "infotext", "inherit", "initial", "inline", "inline-axis",
"inline-block", "inline-table", "inset", "inside", "intrinsic", "invert",
"italic", "justify", "kannada", "katakana", "katakana-iroha", "khmer",
"landscape", "lao", "large", "larger", "left", "level", "lighter",
"line-through", "linear", "lines", "list-item", "listbox", "listitem",
"local", "logical", "loud", "lower", "lower-alpha", "lower-armenian",
"lower-greek", "lower-hexadecimal", "lower-latin", "lower-norwegian",
"lower-roman", "lowercase", "ltr", "malayalam", "match",
"media-controls-background", "media-current-time-display",
"media-fullscreen-button", "media-mute-button", "media-play-button",
"media-return-to-realtime-button", "media-rewind-button",
"media-seek-back-button", "media-seek-forward-button", "media-slider",
"media-sliderthumb", "media-time-remaining-display", "media-volume-slider",
"media-volume-slider-container", "media-volume-sliderthumb", "medium",
"menu", "menulist", "menulist-button", "menulist-text",
"menulist-textfield", "menutext", "message-box", "middle", "min-intrinsic",
"mix", "mongolian", "monospace", "move", "multiple", "myanmar", "n-resize",
"narrower", "navy", "ne-resize", "nesw-resize", "no-close-quote", "no-drop",
"no-open-quote", "no-repeat", "none", "normal", "not-allowed", "nowrap",
"ns-resize", "nw-resize", "nwse-resize", "oblique", "octal", "open-quote",
"optimizeLegibility", "optimizeSpeed", "oriya", "oromo", "outset",
"outside", "overlay", "overline", "padding", "padding-box", "painted",
"paused", "persian", "plus-darker", "plus-lighter", "pointer", "portrait",
"pre", "pre-line", "pre-wrap", "preserve-3d", "progress", "push-button",
"radio", "read-only", "read-write", "read-write-plaintext-only", "relative",
"repeat", "repeat-x", "repeat-y", "reset", "reverse", "rgb", "rgba",
"ridge", "right", "round", "row-resize", "rtl", "run-in", "running",
"s-resize", "sans-serif", "scroll", "scrollbar", "se-resize", "searchfield",
"searchfield-cancel-button", "searchfield-decoration",
"searchfield-results-button", "searchfield-results-decoration",
"semi-condensed", "semi-expanded", "separate", "serif", "show", "sidama",
"single", "skip-white-space", "slide", "slider-horizontal",
"slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", "slow",
"small", "small-caps", "small-caption", "smaller", "solid", "somali",
"source-atop", "source-in", "source-out", "source-over", "space", "square",
"square-button", "start", "static", "status-bar", "stretch", "stroke",
"sub", "subpixel-antialiased", "super", "sw-resize", "table",
"table-caption", "table-cell", "table-column", "table-column-group",
"table-footer-group", "table-header-group", "table-row", "table-row-group",
"telugu", "text", "text-bottom", "text-top", "textarea", "textfield", "thai",
"thick", "thin", "threeddarkshadow", "threedface", "threedhighlight",
"threedlightshadow", "threedshadow", "tibetan", "tigre", "tigrinya-er",
"tigrinya-er-abegede", "tigrinya-et", "tigrinya-et-abegede", "to", "top",
"transparent", "ultra-condensed", "ultra-expanded", "underline", "up",
"upper-alpha", "upper-armenian", "upper-greek", "upper-hexadecimal",
"upper-latin", "upper-norwegian", "upper-roman", "uppercase", "urdu", "url",
"vertical", "vertical-text", "visible", "visibleFill", "visiblePainted",
"visibleStroke", "visual", "w-resize", "wait", "wave", "white", "wider",
"window", "windowframe", "windowtext", "x-large", "x-small", "xor",
"xx-large", "xx-small", "yellow"
]);
function keySet(array) { var keys = {}; for (var i = 0; i < array.length; ++i) keys[array[i]] = true; return keys; }
function ret(style, tp) {type = tp; return style;}
function tokenBase(stream, state) {
var ch = stream.next();
if (ch == "@") {stream.eatWhile(/[\w\\\-]/); return ret("def", stream.current());}
else if (ch == "/" && stream.eat("*")) {
state.tokenize = tokenCComment;
return tokenCComment(stream, state);
}
else if (ch == "<" && stream.eat("!")) {
state.tokenize = tokenSGMLComment;
return tokenSGMLComment(stream, state);
}
else if (ch == "=") ret(null, "compare");
else if ((ch == "~" || ch == "|") && stream.eat("=")) return ret(null, "compare");
else if (ch == "\"" || ch == "'") {
state.tokenize = tokenString(ch);
return state.tokenize(stream, state);
}
else if (ch == "#") {
stream.eatWhile(/[\w\\\-]/);
return ret("atom", "hash");
}
else if (ch == "!") {
stream.match(/^\s*\w*/);
return ret("keyword", "important");
}
else if (/\d/.test(ch)) {
stream.eatWhile(/[\w.%]/);
return ret("number", "unit");
}
else if (ch === "-") {
if (/\d/.test(stream.peek())) {
stream.eatWhile(/[\w.%]/);
return ret("number", "unit");
} else if (stream.match(/^[^-]+-/)) {
return ret("meta", type);
}
}
else if (/[,+>*\/]/.test(ch)) {
return ret(null, "select-op");
}
else if (ch == "." && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) {
return ret("qualifier", type);
}
else if (ch == ":") {
return ret("operator", ch);
}
else if (/[;{}\[\]\(\)]/.test(ch)) {
return ret(null, ch);
}
else {
stream.eatWhile(/[\w\\\-]/);
return ret("property", "variable");
}
}
function tokenCComment(stream, state) {
var maybeEnd = false, ch;
while ((ch = stream.next()) != null) {
if (maybeEnd && ch == "/") {
state.tokenize = tokenBase;
break;
}
maybeEnd = (ch == "*");
}
return ret("comment", "comment");
}
function tokenSGMLComment(stream, state) {
var dashes = 0, ch;
while ((ch = stream.next()) != null) {
if (dashes >= 2 && ch == ">") {
state.tokenize = tokenBase;
break;
}
dashes = (ch == "-") ? dashes + 1 : 0;
}
return ret("comment", "comment");
}
function tokenString(quote) {
return function(stream, state) {
var escaped = false, ch;
while ((ch = stream.next()) != null) {
if (ch == quote && !escaped)
break;
escaped = !escaped && ch == "\\";
}
if (!escaped) state.tokenize = tokenBase;
return ret("string", "string");
};
}
return {
startState: function(base) {
return {tokenize: tokenBase,
baseIndent: base || 0,
stack: []};
},
token: function(stream, state) {
// Use these terms when applicable (see http://www.xanthir.com/blog/b4E50)
//
// rule** or **ruleset:
// A selector + braces combo, or an at-rule.
//
// declaration block:
// A sequence of declarations.
//
// declaration:
// A property + colon + value combo.
//
// property value:
// The entire value of a property.
//
// component value:
// A single piece of a property value. Like the 5px in
// text-shadow: 0 0 5px blue;. Can also refer to things that are
// multiple terms, like the 1-4 terms that make up the background-size
// portion of the background shorthand.
//
// term:
// The basic unit of author-facing CSS, like a single number (5),
// dimension (5px), string ("foo"), or function. Officially defined
// by the CSS 2.1 grammar (look for the 'term' production)
//
//
// simple selector:
// A single atomic selector, like a type selector, an attr selector, a
// class selector, etc.
//
// compound selector:
// One or more simple selectors without a combinator. div.example is
// compound, div > .example is not.
//
// complex selector:
// One or more compound selectors chained with combinators.
//
// combinator:
// The parts of selectors that express relationships. There are four
// currently - the space (descendant combinator), the greater-than
// bracket (child combinator), the plus sign (next sibling combinator),
// and the tilda (following sibling combinator).
//
// sequence of selectors:
// One or more of the named type of selector chained with commas.
if (stream.eatSpace()) return null;
var style = state.tokenize(stream, state);
// Changing style returned based on context
var context = state.stack[state.stack.length-1];
if (style == "property") {
if (context == "propertyValue"){
if (valueKeywords[stream.current()]) {
style = "string-2";
} else if (colorKeywords[stream.current()]) {
style = "keyword";
} else {
style = "variable-2";
}
} else if (context == "rule") {
if (!propertyKeywords[stream.current()]) {
style += " error";
}
} else if (!context || context == "@media{") {
style = "tag";
} else if (context == "@media") {
if (atMediaTypes[stream.current()]) {
style = "attribute"; // Known attribute
} else if (/^(only|not)$/i.test(stream.current())) {
style = "keyword";
} else if (stream.current().toLowerCase() == "and") {
style = "error"; // "and" is only allowed in @mediaType
} else if (atMediaFeatures[stream.current()]) {
style = "error"; // Known property, should be in @mediaType(
} else {
// Unknown, expecting keyword or attribute, assuming attribute
style = "attribute error";
}
} else if (context == "@mediaType") {
if (atMediaTypes[stream.current()]) {
style = "attribute";
} else if (stream.current().toLowerCase() == "and") {
style = "operator";
} else if (/^(only|not)$/i.test(stream.current())) {
style = "error"; // Only allowed in @media
} else if (atMediaFeatures[stream.current()]) {
style = "error"; // Known property, should be in parentheses
} else {
// Unknown attribute or property, but expecting property (preceded
// by "and"). Should be in parentheses
style = "error";
}
} else if (context == "@mediaType(") {
if (propertyKeywords[stream.current()]) {
// do nothing, remains "property"
} else if (atMediaTypes[stream.current()]) {
style = "error"; // Known property, should be in parentheses
} else if (stream.current().toLowerCase() == "and") {
style = "operator";
} else if (/^(only|not)$/i.test(stream.current())) {
style = "error"; // Only allowed in @media
} else {
style += " error";
}
} else {
style = "error";
}
} else if (style == "atom") {
if(!context || context == "@media{") {
style = "builtin";
} else if (context == "propertyValue") {
if (!/^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/.test(stream.current())) {
style += " error";
}
} else {
style = "error";
}
} else if (context == "@media" && type == "{") {
style = "error";
}
// Push/pop context stack
if (type == "{") {
if (context == "@media" || context == "@mediaType") {
state.stack.pop();
state.stack[state.stack.length-1] = "@media{";
}
else state.stack.push("rule");
}
else if (type == "}") {
state.stack.pop();
if (context == "propertyValue") state.stack.pop();
}
else if (type == "@media") state.stack.push("@media");
else if (context == "@media" && /\b(keyword|attribute)\b/.test(style))
state.stack.push("@mediaType");
else if (context == "@mediaType" && stream.current() == ",") state.stack.pop();
else if (context == "@mediaType" && type == "(") state.stack.push("@mediaType(");
else if (context == "@mediaType(" && type == ")") state.stack.pop();
else if (context == "rule" && type == ":") state.stack.push("propertyValue");
else if (context == "propertyValue" && type == ";") state.stack.pop();
return style;
},
indent: function(state, textAfter) {
var n = state.stack.length;
if (/^\}/.test(textAfter))
n -= state.stack[state.stack.length-1] == "propertyValue" ? 2 : 1;
return state.baseIndent + n * indentUnit;
},
electricChars: "}"
};
});
CodeMirror.defineMIME("text/css", "css");
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: CSS mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="css.js"></script>
<style>.CodeMirror {background: #f8f8f8;}</style>
<link rel="stylesheet" href="../../doc/docs.css">
</head>
<body>
<h1>CodeMirror: CSS mode</h1>
<form><textarea id="code" name="code">
/* Some example CSS */
@import url("something.css");
body {
margin: 0;
padding: 3em 6em;
font-family: tahoma, arial, sans-serif;
color: #000;
}
#navigation a {
font-weight: bold;
text-decoration: none !important;
}
h1 {
font-size: 2.5em;
}
h2 {
font-size: 1.7em;
}
h1:before, h2:before {
content: "::";
}
code {
font-family: courier, monospace;
font-size: 80%;
color: #418A8A;
}
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
</script>
<p><strong>MIME types defined:</strong> <code>text/css</code>.</p>
<p><strong>Parsing/Highlighting Tests:</strong> <a href="../../test/index.html#css_*">normal</a>, <a href="../../test/index.html#verbose,css_*">verbose</a>.</p>
</body>
</html>
// Initiate ModeTest and set defaults
var MT = ModeTest;
MT.modeName = 'css';
MT.modeOptions = {};
// Requires at least one media query
MT.testMode(
'atMediaEmpty',
'@media { }',
[
'def', '@media',
null, ' ',
'error', '{',
null, ' }'
]
);
MT.testMode(
'atMediaMultiple',
'@media not screen and (color), not print and (color) { }',
[
'def', '@media',
null, ' ',
'keyword', 'not',
null, ' ',
'attribute', 'screen',
null, ' ',
'operator', 'and',
null, ' (',
'property', 'color',
null, '), ',
'keyword', 'not',
null, ' ',
'attribute', 'print',
null, ' ',
'operator', 'and',
null, ' (',
'property', 'color',
null, ') { }'
]
);
MT.testMode(
'atMediaCheckStack',
'@media screen { } foo { }',
[
'def', '@media',
null, ' ',
'attribute', 'screen',
null, ' { } ',
'tag', 'foo',
null, ' { }'
]
);
MT.testMode(
'atMediaCheckStack',
'@media screen (color) { } foo { }',
[
'def', '@media',
null, ' ',
'attribute', 'screen',
null, ' (',
'property', 'color',
null, ') { } ',
'tag', 'foo',
null, ' { }'
]
);
MT.testMode(
'atMediaCheckStackInvalidAttribute',
'@media foobarhello { } foo { }',
[
'def', '@media',
null, ' ',
'attribute error', 'foobarhello',
null, ' { } ',
'tag', 'foo',
null, ' { }'
]
);
// Error, because "and" is only allowed immediately preceding a media expression
MT.testMode(
'atMediaInvalidAttribute',
'@media foobarhello { }',
[
'def', '@media',
null, ' ',
'attribute error', 'foobarhello',
null, ' { }'
]
);
// Error, because "and" is only allowed immediately preceding a media expression
MT.testMode(
'atMediaInvalidAnd',
'@media and screen { }',
[
'def', '@media',
null, ' ',
'error', 'and',
null, ' ',
'attribute', 'screen',
null, ' { }'
]
);
// Error, because "not" is only allowed as the first item in each media query
MT.testMode(
'atMediaInvalidNot',
'@media screen not (not) { }',
[
'def', '@media',
null, ' ',
'attribute', 'screen',
null, ' ',
'error', 'not',
null, ' (',
'error', 'not',
null, ') { }'
]
);
// Error, because "only" is only allowed as the first item in each media query
MT.testMode(
'atMediaInvalidOnly',
'@media screen only (only) { }',
[
'def', '@media',
null, ' ',
'attribute', 'screen',
null, ' ',
'error', 'only',
null, ' (',
'error', 'only',
null, ') { }'
]
);
// Error, because "foobarhello" is neither a known type or property, but
// property was expected (after "and"), and it should be in parenthese.
MT.testMode(
'atMediaUnknownType',
'@media screen and foobarhello { }',
[
'def', '@media',
null, ' ',
'attribute', 'screen',
null, ' ',
'operator', 'and',
null, ' ',
'error', 'foobarhello',
null, ' { }'
]
);
// Error, because "color" is not a known type, but is a known property, and
// should be in parentheses.
MT.testMode(
'atMediaInvalidType',
'@media screen and color { }',
[
'def', '@media',
null, ' ',
'attribute', 'screen',
null, ' ',
'operator', 'and',
null, ' ',
'error', 'color',
null, ' { }'
]
);
// Error, because "print" is not a known property, but is a known type,
// and should not be in parenthese.
MT.testMode(
'atMediaInvalidProperty',
'@media screen and (print) { }',
[
'def', '@media',
null, ' ',
'attribute', 'screen',
null, ' ',
'operator', 'and',
null, ' (',
'error', 'print',
null, ') { }'
]
);
// Soft error, because "foobarhello" is not a known property or type.
MT.testMode(
'atMediaUnknownProperty',
'@media screen and (foobarhello) { }',
[
'def', '@media',
null, ' ',
'attribute', 'screen',
null, ' ',
'operator', 'and',
null, ' (',
'property error', 'foobarhello',
null, ') { }'
]
);
MT.testMode(
'tagSelector',
'foo { }',
[
'tag', 'foo',
null, ' { }'
]
);
MT.testMode(
'classSelector',
'.foo-bar_hello { }',
[
'qualifier', '.foo-bar_hello',
null, ' { }'
]
);
MT.testMode(
'idSelector',
'#foo { #foo }',
[
'builtin', '#foo',
null, ' { ',
'error', '#foo',
null, ' }'
]
);
MT.testMode(
'tagSelectorUnclosed',
'foo { margin: 0 } bar { }',
[
'tag', 'foo',
null, ' { ',
'property', 'margin',
'operator', ':',
null, ' ',
'number', '0',
null, ' } ',
'tag', 'bar',
null, ' { }'
]
);
MT.testMode(
'tagStringNoQuotes',
'foo { font-family: hello world; }',
[
'tag', 'foo',
null, ' { ',
'property', 'font-family',
'operator', ':',
null, ' ',
'variable-2', 'hello',
null, ' ',
'variable-2', 'world',
null, '; }'
]
);
MT.testMode(
'tagStringDouble',
'foo { font-family: "hello world"; }',
[
'tag', 'foo',
null, ' { ',
'property', 'font-family',
'operator', ':',
null, ' ',
'string', '"hello world"',
null, '; }'
]
);
MT.testMode(
'tagStringSingle',
'foo { font-family: \'hello world\'; }',
[
'tag', 'foo',
null, ' { ',
'property', 'font-family',
'operator', ':',
null, ' ',
'string', '\'hello world\'',
null, '; }'
]
);
MT.testMode(
'tagColorKeyword',
'foo { color: black; }',
[
'tag', 'foo',
null, ' { ',
'property', 'color',
'operator', ':',
null, ' ',
'keyword', 'black',
null, '; }'
]
);
MT.testMode(
'tagColorHex3',
'foo { background: #fff; }',
[
'tag', 'foo',
null, ' { ',
'property', 'background',
'operator', ':',
null, ' ',
'atom', '#fff',
null, '; }'
]
);
MT.testMode(
'tagColorHex6',
'foo { background: #ffffff; }',
[
'tag', 'foo',
null, ' { ',
'property', 'background',
'operator', ':',
null, ' ',
'atom', '#ffffff',
null, '; }'
]
);
MT.testMode(
'tagColorHex4',
'foo { background: #ffff; }',
[
'tag', 'foo',
null, ' { ',
'property', 'background',
'operator', ':',
null, ' ',
'atom error', '#ffff',
null, '; }'
]
);
MT.testMode(
'tagColorHexInvalid',
'foo { background: #ffg; }',
[
'tag', 'foo',
null, ' { ',
'property', 'background',
'operator', ':',
null, ' ',
'atom error', '#ffg',
null, '; }'
]
);
MT.testMode(
'tagNegativeNumber',
'foo { margin: -5px; }',
[
'tag', 'foo',
null, ' { ',
'property', 'margin',
'operator', ':',
null, ' ',
'number', '-5px',
null, '; }'
]
);
MT.testMode(
'tagPositiveNumber',
'foo { padding: 5px; }',
[
'tag', 'foo',
null, ' { ',
'property', 'padding',
'operator', ':',
null, ' ',
'number', '5px',
null, '; }'
]
);
MT.testMode(
'tagVendor',
'foo { -foo-box-sizing: -foo-border-box; }',
[
'tag', 'foo',
null, ' { ',
'meta', '-foo-',
'property', 'box-sizing',
'operator', ':',
null, ' ',
'meta', '-foo-',
'string-2', 'border-box',
null, '; }'
]
);
MT.testMode(
'tagBogusProperty',
'foo { barhelloworld: 0; }',
[
'tag', 'foo',
null, ' { ',
'property error', 'barhelloworld',
'operator', ':',
null, ' ',
'number', '0',
null, '; }'
]
);
MT.testMode(
'tagTwoProperties',
'foo { margin: 0; padding: 0; }',
[
'tag', 'foo',
null, ' { ',
'property', 'margin',
'operator', ':',
null, ' ',
'number', '0',
null, '; ',
'property', 'padding',
'operator', ':',
null, ' ',
'number', '0',
null, '; }'
]
);
//
//MT.testMode(
// 'tagClass',
// '@media only screen and (min-width: 500px), print {foo.bar#hello { color: black !important; background: #f00; margin: -5px; padding: 5px; -foo-box-sizing: border-box; } /* world */}',
// [
// 'def', '@media',
// null, ' ',
// 'keyword', 'only',
// null, ' ',
// 'attribute', 'screen',
// null, ' ',
// 'operator', 'and',
// null, ' ',
// 'bracket', '(',
// 'property', 'min-width',
// 'operator', ':',
// null, ' ',
// 'number', '500px',
// 'bracket', ')',
// null, ', ',
// 'attribute', 'print',
// null, ' {',
// 'tag', 'foo',
// 'qualifier', '.bar',
// 'header', '#hello',
// null, ' { ',
// 'property', 'color',
// 'operator', ':',
// null, ' ',
// 'keyword', 'black',
// null, ' ',
// 'keyword', '!important',
// null, '; ',
// 'property', 'background',
// 'operator', ':',
// null, ' ',
// 'atom', '#f00',
// null, '; ',
// 'property', 'padding',
// 'operator', ':',
// null, ' ',
// 'number', '5px',
// null, '; ',
// 'property', 'margin',
// 'operator', ':',
// null, ' ',
// 'number', '-5px',
// null, '; ',
// 'meta', '-foo-',
// 'property', 'box-sizing',
// 'operator', ':',
// null, ' ',
// 'string-2', 'border-box',
// null, '; } ',
// 'comment', '/* world */',
// null, '}'
// ]
//);
CodeMirror.defineMode("diff", function() {
var TOKEN_NAMES = {
'+': 'tag',
'-': 'string',
'@': 'meta'
};
return {
token: function(stream) {
var tw_pos = stream.string.search(/[\t ]+?$/);
if (!stream.sol() || tw_pos === 0) {
stream.skipToEnd();
return ("error " + (
TOKEN_NAMES[stream.string.charAt(0)] || '')).replace(/ $/, '');
}
var token_name = TOKEN_NAMES[stream.peek()] || stream.skipToEnd();
if (tw_pos === -1) {
stream.skipToEnd();
} else {
stream.pos = tw_pos;
}
return token_name;
}
};
});
CodeMirror.defineMIME("text/x-diff", "diff");
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Diff mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="diff.js"></script>
<style>
.CodeMirror {border-top: 1px solid #ddd; border-bottom: 1px solid #ddd;}
span.cm-meta {color: #a0b !important;}
span.cm-error { background-color: black; opacity: 0.4;}
span.cm-error.cm-string { background-color: red; }
span.cm-error.cm-tag { background-color: #2b2; }
</style>
<link rel="stylesheet" href="../../doc/docs.css">
</head>
<body>
<h1>CodeMirror: Diff mode</h1>
<form><textarea id="code" name="code">
diff --git a/index.html b/index.html
index c1d9156..7764744 100644
--- a/index.html
+++ b/index.html
@@ -95,7 +95,8 @@ StringStream.prototype = {
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
- autoMatchBrackets: true
+ autoMatchBrackets: true,
+ onGutterClick: function(x){console.log(x);}
});
</script>
</body>
diff --git a/lib/codemirror.js b/lib/codemirror.js
index 04646a9..9a39cc7 100644
--- a/lib/codemirror.js
+++ b/lib/codemirror.js
@@ -399,10 +399,16 @@ var CodeMirror = (function() {
}
function onMouseDown(e) {
- var start = posFromMouse(e), last = start;
+ var start = posFromMouse(e), last = start, target = e.target();
if (!start) return;
setCursor(start.line, start.ch, false);
if (e.button() != 1) return;
+ if (target.parentNode == gutter) {
+ if (options.onGutterClick)
+ options.onGutterClick(indexOf(gutter.childNodes, target) + showingFrom);
+ return;
+ }
+
if (!focused) onFocus();
e.stop();
@@ -808,7 +814,7 @@ var CodeMirror = (function() {
for (var i = showingFrom; i < showingTo; ++i) {
var marker = lines[i].gutterMarker;
if (marker) html.push('<div class="' + marker.style + '">' + htmlEscape(marker.text) + '</div>');
- else html.push("<div>" + (options.lineNumbers ? i + 1 : "\u00a0") + "</div>");
+ else html.push("<div>" + (options.lineNumbers ? i + options.firstLineNumber : "\u00a0") + "</div>");
}
gutter.style.display = "none"; // TODO test whether this actually helps
gutter.innerHTML = html.join("");
@@ -1371,10 +1377,8 @@ var CodeMirror = (function() {
if (option == "parser") setParser(value);
else if (option === "lineNumbers") setLineNumbers(value);
else if (option === "gutter") setGutter(value);
- else if (option === "readOnly") options.readOnly = value;
- else if (option === "indentUnit") {options.indentUnit = indentUnit = value; setParser(options.parser);}
- else if (/^(?:enterMode|tabMode|indentWithTabs|readOnly|autoMatchBrackets|undoDepth)$/.test(option)) options[option] = value;
- else throw new Error("Can't set option " + option);
+ else if (option === "indentUnit") {options.indentUnit = value; setParser(options.parser);}
+ else options[option] = value;
},
cursorCoords: cursorCoords,
undo: operation(undo),
@@ -1402,7 +1406,8 @@ var CodeMirror = (function() {
replaceRange: operation(replaceRange),
operation: function(f){return operation(f)();},
- refresh: function(){updateDisplay([{from: 0, to: lines.length}]);}
+ refresh: function(){updateDisplay([{from: 0, to: lines.length}]);},
+ getInputField: function(){return input;}
};
return instance;
}
@@ -1420,6 +1425,7 @@ var CodeMirror = (function() {
readOnly: false,
onChange: null,
onCursorActivity: null,
+ onGutterClick: null,
autoMatchBrackets: false,
workTime: 200,
workDelay: 300,
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
</script>
<p><strong>MIME types defined:</strong> <code>text/x-diff</code>.</p>
</body>
</html>
CodeMirror.defineMode("ecl", function(config) {
function words(str) {
var obj = {}, words = str.split(" ");
for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
return obj;
}
function metaHook(stream, state) {
if (!state.startOfLine) return false;
stream.skipToEnd();
return "meta";
}
function tokenAtString(stream, state) {
var next;
while ((next = stream.next()) != null) {
if (next == '"' && !stream.eat('"')) {
state.tokenize = null;
break;
}
}
return "string";
}
var indentUnit = config.indentUnit;
var keyword = words("abs acos allnodes ascii asin asstring atan atan2 ave case choose choosen choosesets clustersize combine correlation cos cosh count covariance cron dataset dedup define denormalize distribute distributed distribution ebcdic enth error evaluate event eventextra eventname exists exp failcode failmessage fetch fromunicode getisvalid global graph group hash hash32 hash64 hashcrc hashmd5 having if index intformat isvalid iterate join keyunicode length library limit ln local log loop map matched matchlength matchposition matchtext matchunicode max merge mergejoin min nolocal nonempty normalize parse pipe power preload process project pull random range rank ranked realformat recordof regexfind regexreplace regroup rejected rollup round roundup row rowdiff sample set sin sinh sizeof soapcall sort sorted sqrt stepped stored sum table tan tanh thisnode topn tounicode transfer trim truncate typeof ungroup unicodeorder variance which workunit xmldecode xmlencode xmltext xmlunicode");
var variable = words("apply assert build buildindex evaluate fail keydiff keypatch loadxml nothor notify output parallel sequential soapcall wait");
var variable_2 = words("__compressed__ all and any as atmost before beginc++ best between case const counter csv descend encrypt end endc++ endmacro except exclusive expire export extend false few first flat from full function group header heading hole ifblock import in interface joined keep keyed last left limit load local locale lookup macro many maxcount maxlength min skew module named nocase noroot noscan nosort not of only opt or outer overwrite packed partition penalty physicallength pipe quote record relationship repeat return right scan self separator service shared skew skip sql store terminator thor threshold token transform trim true type unicodeorder unsorted validate virtual whole wild within xml xpath");
var variable_3 = words("ascii big_endian boolean data decimal ebcdic integer pattern qstring real record rule set of string token udecimal unicode unsigned varstring varunicode");
var builtin = words("checkpoint deprecated failcode failmessage failure global independent onwarning persist priority recovery stored success wait when");
var blockKeywords = words("catch class do else finally for if switch try while");
var atoms = words("true false null");
var hooks = {"#": metaHook};
var multiLineStrings;
var isOperatorChar = /[+\-*&%=<>!?|\/]/;
var curPunc;
function tokenBase(stream, state) {
var ch = stream.next();
if (hooks[ch]) {
var result = hooks[ch](stream, state);
if (result !== false) return result;
}
if (ch == '"' || ch == "'") {
state.tokenize = tokenString(ch);
return state.tokenize(stream, state);
}
if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
curPunc = ch;
return null;
}
if (/\d/.test(ch)) {
stream.eatWhile(/[\w\.]/);
return "number";
}
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\$_]/);
var cur = stream.current().toLowerCase();
if (keyword.propertyIsEnumerable(cur)) {
if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
return "keyword";
} else if (variable.propertyIsEnumerable(cur)) {
if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
return "variable";
} else if (variable_2.propertyIsEnumerable(cur)) {
if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
return "variable-2";
} else if (variable_3.propertyIsEnumerable(cur)) {
if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
return "variable-3";
} else if (builtin.propertyIsEnumerable(cur)) {
if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
return "builtin";
} else { //Data types are of from KEYWORD##
var i = cur.length - 1;
while(i >= 0 && (!isNaN(cur[i]) || cur[i] == '_'))
--i;
if (i > 0) {
var cur2 = cur.substr(0, i + 1);
if (variable_3.propertyIsEnumerable(cur2)) {
if (blockKeywords.propertyIsEnumerable(cur2)) curPunc = "newstatement";
return "variable-3";
}
}
}
if (atoms.propertyIsEnumerable(cur)) return "atom";
return null;
}
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 && next == "\\";
}
if (end || !(escaped || multiLineStrings))
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) {
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 (stream.eatSpace()) return null;
curPunc = null;
var style = (state.tokenize || tokenBase)(stream, state);
if (style == "comment" || style == "meta") return style;
if (ctx.align == null) ctx.align = true;
if ((curPunc == ";" || curPunc == ":") && ctx.type == "statement") popContext(state);
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;
return style;
},
indent: function(state, textAfter) {
if (state.tokenize != tokenBase && state.tokenize != null) return 0;
var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev;
var closing = firstChar == ctx.type;
if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : indentUnit);
else if (ctx.align) return ctx.column + (closing ? 0 : 1);
else return ctx.indented + (closing ? 0 : indentUnit);
},
electricChars: "{}"
};
});
CodeMirror.defineMIME("text/x-ecl", "ecl");
<!doctype html>
<html>
<head>
<title>CodeMirror: ECL mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="ecl.js"></script>
<link rel="stylesheet" href="../../doc/docs.css">
<style>.CodeMirror {border: 1px solid black;}</style>
</head>
<body>
<h1>CodeMirror: ECL mode</h1>
<form><textarea id="code" name="code">
/*
sample useless code to demonstrate ecl syntax highlighting
this is a multiline comment!
*/
// this is a singleline comment!
import ut;
r :=
record
string22 s1 := '123';
integer4 i1 := 123;
end;
#option('tmp', true);
d := dataset('tmp::qb', r, thor);
output(d);
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
tabMode: "indent",
matchBrackets: true,
});
</script>
<p>Based on CodeMirror's clike mode. For more information see <a href="http://hpccsystems.com">HPCC Systems</a> web site.</p>
<p><strong>MIME types defined:</strong> <code>text/x-ecl</code>.</p>
</body>
</html>
// block; "begin", "case", "fun", "if", "receive", "try": closed by "end"
// block internal; "after", "catch", "of"
// guard; "when", closed by "->"
// "->" opens a clause, closed by ";" or "."
// "<<" opens a binary, closed by ">>"
// "," appears in arglists, lists, tuples and terminates lines of code
// "." resets indentation to 0
// obsolete; "cond", "let", "query"
CodeMirror.defineMIME("text/x-erlang", "erlang");
CodeMirror.defineMode("erlang", function(cmCfg, modeCfg) {
function rval(state,stream,type) {
// distinguish between "." as terminator and record field operator
if (type == "record") {
state.context = "record";
}else{
state.context = false;
}
// remember last significant bit on last line for indenting
if (type != "whitespace" && type != "comment") {
state.lastToken = stream.current();
}
// erlang -> CodeMirror tag
switch (type) {
case "atom": return "atom";
case "attribute": return "attribute";
case "builtin": return "builtin";
case "comment": return "comment";
case "fun": return "meta";
case "function": return "tag";
case "guard": return "property";
case "keyword": return "keyword";
case "macro": return "variable-2";
case "number": return "number";
case "operator": return "operator";
case "record": return "bracket";
case "string": return "string";
case "type": return "def";
case "variable": return "variable";
case "error": return "error";
case "separator": return null;
case "open_paren": return null;
case "close_paren": return null;
default: return null;
}
}
var typeWords = [
"-type", "-spec", "-export_type", "-opaque"];
var keywordWords = [
"after","begin","catch","case","cond","end","fun","if",
"let","of","query","receive","try","when"];
var separatorWords = [
"->",";",":",".",","];
var operatorWords = [
"and","andalso","band","bnot","bor","bsl","bsr","bxor",
"div","not","or","orelse","rem","xor"];
var symbolWords = [
"+","-","*","/",">",">=","<","=<","=:=","==","=/=","/=","||","<-"];
var openParenWords = [
"<<","(","[","{"];
var closeParenWords = [
"}","]",")",">>"];
var guardWords = [
"is_atom","is_binary","is_bitstring","is_boolean","is_float",
"is_function","is_integer","is_list","is_number","is_pid",
"is_port","is_record","is_reference","is_tuple",
"atom","binary","bitstring","boolean","function","integer","list",
"number","pid","port","record","reference","tuple"];
var bifWords = [
"abs","adler32","adler32_combine","alive","apply","atom_to_binary",
"atom_to_list","binary_to_atom","binary_to_existing_atom",
"binary_to_list","binary_to_term","bit_size","bitstring_to_list",
"byte_size","check_process_code","contact_binary","crc32",
"crc32_combine","date","decode_packet","delete_module",
"disconnect_node","element","erase","exit","float","float_to_list",
"garbage_collect","get","get_keys","group_leader","halt","hd",
"integer_to_list","internal_bif","iolist_size","iolist_to_binary",
"is_alive","is_atom","is_binary","is_bitstring","is_boolean",
"is_float","is_function","is_integer","is_list","is_number","is_pid",
"is_port","is_process_alive","is_record","is_reference","is_tuple",
"length","link","list_to_atom","list_to_binary","list_to_bitstring",
"list_to_existing_atom","list_to_float","list_to_integer",
"list_to_pid","list_to_tuple","load_module","make_ref","module_loaded",
"monitor_node","node","node_link","node_unlink","nodes","notalive",
"now","open_port","pid_to_list","port_close","port_command",
"port_connect","port_control","pre_loaded","process_flag",
"process_info","processes","purge_module","put","register",
"registered","round","self","setelement","size","spawn","spawn_link",
"spawn_monitor","spawn_opt","split_binary","statistics",
"term_to_binary","time","throw","tl","trunc","tuple_size",
"tuple_to_list","unlink","unregister","whereis"];
// ignored for indenting purposes
var ignoreWords = [
",", ":", "catch", "after", "of", "cond", "let", "query"];
var smallRE = /[a-z_]/;
var largeRE = /[A-Z_]/;
var digitRE = /[0-9]/;
var octitRE = /[0-7]/;
var anumRE = /[a-z_A-Z0-9]/;
var symbolRE = /[\+\-\*\/<>=\|:]/;
var openParenRE = /[<\(\[\{]/;
var closeParenRE = /[>\)\]\}]/;
var sepRE = /[\->\.,:;]/;
function isMember(element,list) {
return (-1 < list.indexOf(element));
}
function isPrev(stream,string) {
var start = stream.start;
var len = string.length;
if (len <= start) {
var word = stream.string.slice(start-len,start);
return word == string;
}else{
return false;
}
}
function tokenize(stream, state) {
if (stream.eatSpace()) {
return rval(state,stream,"whitespace");
}
// attributes and type specs
if ((peekToken(state).token == "" || peekToken(state).token == ".") &&
stream.peek() == '-') {
stream.next();
if (stream.eat(smallRE) && stream.eatWhile(anumRE)) {
if (isMember(stream.current(),typeWords)) {
return rval(state,stream,"type");
}else{
return rval(state,stream,"attribute");
}
}
stream.backUp(1);
}
var ch = stream.next();
// comment
if (ch == '%') {
stream.skipToEnd();
return rval(state,stream,"comment");
}
// macro
if (ch == '?') {
stream.eatWhile(anumRE);
return rval(state,stream,"macro");
}
// record
if ( ch == "#") {
stream.eatWhile(anumRE);
return rval(state,stream,"record");
}
// char
if ( ch == "$") {
if (stream.next() == "\\") {
if (!stream.eatWhile(octitRE)) {
stream.next();
}
}
return rval(state,stream,"string");
}
// quoted atom
if (ch == '\'') {
if (singleQuote(stream)) {
return rval(state,stream,"atom");
}else{
return rval(state,stream,"error");
}
}
// string
if (ch == '"') {
if (doubleQuote(stream)) {
return rval(state,stream,"string");
}else{
return rval(state,stream,"error");
}
}
// variable
if (largeRE.test(ch)) {
stream.eatWhile(anumRE);
return rval(state,stream,"variable");
}
// atom/keyword/BIF/function
if (smallRE.test(ch)) {
stream.eatWhile(anumRE);
if (stream.peek() == "/") {
stream.next();
if (stream.eatWhile(digitRE)) {
return rval(state,stream,"fun"); // f/0 style fun
}else{
stream.backUp(1);
return rval(state,stream,"atom");
}
}
var w = stream.current();
if (isMember(w,keywordWords)) {
pushToken(state,stream);
return rval(state,stream,"keyword");
}
if (stream.peek() == "(") {
// 'put' and 'erlang:put' are bifs, 'foo:put' is not
if (isMember(w,bifWords) &&
(!isPrev(stream,":") || isPrev(stream,"erlang:"))) {
return rval(state,stream,"builtin");
}else{
return rval(state,stream,"function");
}
}
if (isMember(w,guardWords)) {
return rval(state,stream,"guard");
}
if (isMember(w,operatorWords)) {
return rval(state,stream,"operator");
}
if (stream.peek() == ":") {
if (w == "erlang") {
return rval(state,stream,"builtin");
} else {
return rval(state,stream,"function");
}
}
return rval(state,stream,"atom");
}
// number
if (digitRE.test(ch)) {
stream.eatWhile(digitRE);
if (stream.eat('#')) {
stream.eatWhile(digitRE); // 16#10 style integer
} else {
if (stream.eat('.')) { // float
stream.eatWhile(digitRE);
}
if (stream.eat(/[eE]/)) {
stream.eat(/[-+]/); // float with exponent
stream.eatWhile(digitRE);
}
}
return rval(state,stream,"number"); // normal integer
}
// open parens
if (nongreedy(stream,openParenRE,openParenWords)) {
pushToken(state,stream);
return rval(state,stream,"open_paren");
}
// close parens
if (nongreedy(stream,closeParenRE,closeParenWords)) {
pushToken(state,stream);
return rval(state,stream,"close_paren");
}
// separators
if (greedy(stream,sepRE,separatorWords)) {
// distinguish between "." as terminator and record field operator
if (state.context == false) {
pushToken(state,stream);
}
return rval(state,stream,"separator");
}
// operators
if (greedy(stream,symbolRE,symbolWords)) {
return rval(state,stream,"operator");
}
return rval(state,stream,null);
}
function nongreedy(stream,re,words) {
if (stream.current().length == 1 && re.test(stream.current())) {
stream.backUp(1);
while (re.test(stream.peek())) {
stream.next();
if (isMember(stream.current(),words)) {
return true;
}
}
stream.backUp(stream.current().length-1);
}
return false;
}
function greedy(stream,re,words) {
if (stream.current().length == 1 && re.test(stream.current())) {
while (re.test(stream.peek())) {
stream.next();
}
while (0 < stream.current().length) {
if (isMember(stream.current(),words)) {
return true;
}else{
stream.backUp(1);
}
}
stream.next();
}
return false;
}
function doubleQuote(stream) {
return quote(stream, '"', '\\');
}
function singleQuote(stream) {
return quote(stream,'\'','\\');
}
function quote(stream,quoteChar,escapeChar) {
while (!stream.eol()) {
var ch = stream.next();
if (ch == quoteChar) {
return true;
}else if (ch == escapeChar) {
stream.next();
}
}
return false;
}
function Token(stream) {
this.token = stream ? stream.current() : "";
this.column = stream ? stream.column() : 0;
this.indent = stream ? stream.indentation() : 0;
}
function myIndent(state,textAfter) {
var indent = cmCfg.indentUnit;
var outdentWords = ["after","catch"];
var token = (peekToken(state)).token;
var wordAfter = takewhile(textAfter,/[^a-z]/);
if (isMember(token,openParenWords)) {
return (peekToken(state)).column+token.length;
}else if (token == "." || token == ""){
return 0;
}else if (token == "->") {
if (wordAfter == "end") {
return peekToken(state,2).column;
}else if (peekToken(state,2).token == "fun") {
return peekToken(state,2).column+indent;
}else{
return (peekToken(state)).indent+indent;
}
}else if (isMember(wordAfter,outdentWords)) {
return (peekToken(state)).indent;
}else{
return (peekToken(state)).column+indent;
}
}
function takewhile(str,re) {
var m = str.match(re);
return m ? str.slice(0,m.index) : str;
}
function popToken(state) {
return state.tokenStack.pop();
}
function peekToken(state,depth) {
var len = state.tokenStack.length;
var dep = (depth ? depth : 1);
if (len < dep) {
return new Token;
}else{
return state.tokenStack[len-dep];
}
}
function pushToken(state,stream) {
var token = stream.current();
var prev_token = peekToken(state).token;
if (isMember(token,ignoreWords)) {
return false;
}else if (drop_both(prev_token,token)) {
popToken(state);
return false;
}else if (drop_first(prev_token,token)) {
popToken(state);
return pushToken(state,stream);
}else{
state.tokenStack.push(new Token(stream));
return true;
}
}
function drop_first(open, close) {
switch (open+" "+close) {
case "when ->": return true;
case "-> end": return true;
case "-> .": return true;
case ". .": return true;
default: return false;
}
}
function drop_both(open, close) {
switch (open+" "+close) {
case "( )": return true;
case "[ ]": return true;
case "{ }": return true;
case "<< >>": return true;
case "begin end": return true;
case "case end": return true;
case "fun end": return true;
case "if end": return true;
case "receive end": return true;
case "try end": return true;
case "-> ;": return true;
default: return false;
}
}
return {
startState:
function() {
return {tokenStack: [],
context: false,
lastToken: null};
},
token:
function(stream, state) {
return tokenize(stream, state);
},
indent:
function(state, textAfter) {
// console.log(state.tokenStack);
return myIndent(state,textAfter);
}
};
});
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Erlang mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="erlang.js"></script>
<link rel="stylesheet" href="../../theme/erlang-dark.css">
<style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
<link rel="stylesheet" href="../../doc/docs.css">
</head>
<body>
<h1>CodeMirror: Erlang mode</h1>
<form><textarea id="code" name="code">
%% -*- mode: erlang; erlang-indent-level: 2 -*-
%%% Created : 7 May 2012 by mats cronqvist <masse@klarna.com>
%% @doc
%% Demonstrates how to print a record.
%% @end
-module('ex').
-author('mats cronqvist').
-export([demo/0,
rec_info/1]).
-record(demo,{a="One",b="Two",c="Three",d="Four"}).
rec_info(demo) -> record_info(fields,demo).
demo() -> expand_recs(?MODULE,#demo{a="A",b="BB"}).
expand_recs(M,List) when is_list(List) ->
[expand_recs(M,L)||L<-List];
expand_recs(M,Tup) when is_tuple(Tup) ->
case tuple_size(Tup) of
L when L < 1 -> Tup;
L ->
try Fields = M:rec_info(element(1,Tup)),
L = length(Fields)+1,
lists:zip(Fields,expand_recs(M,tl(tuple_to_list(Tup))))
catch _:_ ->
list_to_tuple(expand_recs(M,tuple_to_list(Tup)))
end
end;
expand_recs(_,Term) ->
Term.
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
matchBrackets: true,
extraKeys: {"Tab": "indentAuto"},
theme: "erlang-dark"
});
</script>
<p><strong>MIME types defined:</strong> <code>text/x-erlang</code>.</p>
</body>
</html>
CodeMirror.defineMode("gfm", function(config, parserConfig) {
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) {
// 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(stream.match(/^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+@)?(?:[a-f0-9]{7,40}\b)/)) {
// User/Project@SHA
// User@SHA
// SHA
return "link";
} else if (stream.match(/^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+)?#[0-9]+\b/)) {
// User/Project#Num
// User#Num
// #Num
return "link";
}
}
if (stream.match(/^((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/i)) {
// URLs
// Taken from http://daringfireball.net/2010/07/improved_regex_for_matching_urls
return "link";
}
stream.next();
return null;
},
blankLine: blankLine
};
CodeMirror.defineMIME("gfmBase", {
name: "markdown",
underscoresBreakWords: false,
fencedCodeBlocks: true
});
return CodeMirror.overlayMode(CodeMirror.getMode(config, "gfmBase"), gfmOverlay);
});
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: GFM mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="../../lib/util/overlay.js"></script>
<script src="../xml/xml.js"></script>
<script src="../markdown/markdown.js"></script>
<script src="gfm.js"></script>
<!-- Code block highlighting modes -->
<script src="../javascript/javascript.js"></script>
<script src="../css/css.js"></script>
<script src="../htmlmixed/htmlmixed.js"></script>
<script src="../clike/clike.js"></script>
<link rel="stylesheet" href="../markdown/markdown.css">
<style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
<link rel="stylesheet" href="../../doc/docs.css">
</head>
<body>
<h1>CodeMirror: GFM mode</h1>
<form><textarea id="code" name="code">
GitHub Flavored Markdown
========================
Everything from markdown plus GFM features:
## URL autolinking
Underscores_are_allowed_between_words.
## Fenced code blocks (and syntax highlighting... someday)
```javascript
for (var i = 0; i &lt; items.length; i++) {
console.log(items[i], i); // log them
}
```
## A bit of GitHub spice
* 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
See http://github.github.com/github-flavored-markdown/.
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
mode: 'gfm',
lineNumbers: true,
matchBrackets: true,
theme: "default"
});
</script>
<p>Optionally depends on other modes for properly highlighted code blocks.</p>
<p><strong>Parsing/Highlighting Tests:</strong> <a href="../../test/index.html#gfm_*">normal</a>, <a href="../../test/index.html#verbose,gfm_*">verbose</a>.</p>
</body>
</html>
// Initiate ModeTest and set defaults
var MT = ModeTest;
MT.modeName = 'gfm';
MT.modeOptions = {};
// Emphasis characters within a word
MT.testMode(
'emInWordAsterisk',
'foo*bar*hello',
[
null, 'foo',
'em', '*bar*',
null, 'hello'
]
);
MT.testMode(
'emInWordUnderscore',
'foo_bar_hello',
[
null, 'foo_bar_hello'
]
);
MT.testMode(
'emStrongUnderscore',
'___foo___ bar',
[
'strong', '__',
'emstrong', '_foo__',
'em', '_',
null, ' bar'
]
);
// Fenced code blocks
MT.testMode(
'fencedCodeBlocks',
'```\nfoo\n\n```\nbar',
[
'comment', '```',
'comment', 'foo',
'comment', '```',
null, 'bar'
]
);
// Fenced code block mode switching
MT.testMode(
'fencedCodeBlockModeSwitching',
'```javascript\nfoo\n\n```\nbar',
[
'comment', '```javascript',
'variable', 'foo',
'comment', '```',
null, 'bar'
]
);
// SHA
MT.testMode(
'SHA',
'foo be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2 bar',
[
null, 'foo ',
'link', 'be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2',
null, ' bar'
]
);
// GitHub highlights hashes 7-40 chars in length
MT.testMode(
'shortSHA',
'foo be6a8cc bar',
[
null, 'foo ',
'link', 'be6a8cc',
null, ' bar'
]
);
// Invalid SHAs
//
// GitHub does not highlight hashes shorter than 7 chars
MT.testMode(
'tooShortSHA',
'foo be6a8c bar',
[
null, 'foo be6a8c bar'
]
);
// GitHub does not highlight hashes longer than 40 chars
MT.testMode(
'longSHA',
'foo be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd22 bar',
[
null, 'foo be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd22 bar'
]
);
MT.testMode(
'badSHA',
'foo be6a8cc1c1ecfe9489fb51e4869af15a13fc2cg2 bar',
[
null, 'foo be6a8cc1c1ecfe9489fb51e4869af15a13fc2cg2 bar'
]
);
// User@SHA
MT.testMode(
'userSHA',
'foo bar@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2 hello',
[
null, 'foo ',
'link', 'bar@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2',
null, ' hello'
]
);
// User/Project@SHA
MT.testMode(
'userProjectSHA',
'foo bar/hello@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2 world',
[
null, 'foo ',
'link', 'bar/hello@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2',
null, ' world'
]
);
// #Num
MT.testMode(
'num',
'foo #1 bar',
[
null, 'foo ',
'link', '#1',
null, ' bar'
]
);
// bad #Num
MT.testMode(
'badNum',
'foo #1bar hello',
[
null, 'foo #1bar hello'
]
);
// User#Num
MT.testMode(
'userNum',
'foo bar#1 hello',
[
null, 'foo ',
'link', 'bar#1',
null, ' hello'
]
);
// User/Project#Num
MT.testMode(
'userProjectNum',
'foo bar/hello#1 world',
[
null, 'foo ',
'link', 'bar/hello#1',
null, ' world'
]
);
// Vanilla links
MT.testMode(
'vanillaLink',
'foo http://www.example.com/ bar',
[
null, 'foo ',
'link', 'http://www.example.com/',
null, ' bar'
]
);
MT.testMode(
'vanillaLinkPunctuation',
'foo http://www.example.com/. bar',
[
null, 'foo ',
'link', 'http://www.example.com/',
null, '. bar'
]
);
MT.testMode(
'vanillaLinkExtension',
'foo http://www.example.com/index.html bar',
[
null, 'foo ',
'link', 'http://www.example.com/index.html',
null, ' bar'
]
);
// Not a link
MT.testMode(
'notALink',
'```css\nfoo {color:black;}\n```http://www.example.com/',
[
'comment', '```css',
'tag', 'foo',
null, ' {',
'property', 'color',
'operator', ':',
'keyword', 'black',
null, ';}',
'comment', '```',
'link', 'http://www.example.com/'
]
);
// Not a link
MT.testMode(
'notALink',
'``foo `bar` http://www.example.com/`` hello',
[
'comment', '``foo `bar` http://www.example.com/``',
null, ' hello'
]
);
// Not a link
MT.testMode(
'notALink',
'`foo\nhttp://www.example.com/\n`foo\n\nhttp://www.example.com/',
[
'comment', '`foo',
'link', 'http://www.example.com/',
'comment', '`foo',
'link', 'http://www.example.com/'
]
);
CodeMirror.defineMode("go", function(config, parserConfig) {
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
};
var atoms = {
"true":true, "false":true, "iota":true, "nil":true, "append":true,
"cap":true, "close":true, "complex":true, "copy":true, "imag":true,
"len":true, "make":true, "new":true, "panic":true, "print":true,
"println":true, "real":true, "recover":true
};
var blockKeywords = {
"else":true, "for":true, "func":true, "if":true, "interface":true,
"select":true, "struct":true, "switch":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\$_]/);
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 && 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) {
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 == "}") ctx = 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 0;
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: "{}:"
};
});
CodeMirror.defineMIME("text/x-go", "go");
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Go mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<link rel="stylesheet" href="../../theme/elegant.css">
<script src="../../lib/codemirror.js"></script>
<script src="go.js"></script>
<link rel="stylesheet" href="../../doc/docs.css">
<style>.CodeMirror {border:1px solid #999; background:#ffc}</style>
</head>
<body>
<h1>CodeMirror: Go mode</h1>
<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>
</body>
</html>
CodeMirror.defineMode("groovy", function(config, parserConfig) {
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 transient " +
"try void volatile while");
var blockKeywords = words("catch class do else finally for if switch try while enum interface def");
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)) {
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";
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) {
return !last || last == "operator" || last == "->" || /[\.\[\{\(,;:]/.test(last) ||
last == "newstatement" || last == "keyword" || last == "proplabel";
}
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)) {
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 0;
var firstChar = textAfter && textAfter.charAt(0), ctx = state.context;
if (ctx.type == "statement" && !expectExpression(state.lastToken)) 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: "{}"
};
});
CodeMirror.defineMIME("text/x-groovy", "groovy");
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Groovy mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="groovy.js"></script>
<link rel="stylesheet" href="../../doc/docs.css">
<style>.CodeMirror {border-top: 1px solid #500; border-bottom: 1px solid #500;}</style>
</head>
<body>
<h1>CodeMirror: Groovy mode</h1>
<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>
</body>
</html>
CodeMirror.defineMode("haskell", function(cmCfg, modeCfg) {
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 = /[0-9]/;
var hexitRE = /[0-9A-Fa-f]/;
var octitRE = /[0-7]/;
var idRE = /[a-z_A-Z0-9']/;
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 "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.eat('.')) {
t = "number";
source.eatWhile(digitRE); // should require at least 1
}
if (source.eat(/[eE]/)) {
t = "number";
source.eat(/[-+]/);
source.eatWhile(digitRE); // should require at least 1
}
return t;
}
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 "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")(
"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",
"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");
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 (w in wellKnownWords) ? wellKnownWords[w] : t;
}
};
});
CodeMirror.defineMIME("text/x-haskell", "haskell");
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Haskell mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="haskell.js"></script>
<link rel="stylesheet" href="../../theme/elegant.css">
<style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
<link rel="stylesheet" href="../../doc/docs.css">
</head>
<body>
<h1>CodeMirror: Haskell mode</h1>
<form><textarea id="code" name="code">
module UniquePerms (
uniquePerms
)
where
-- | Find all unique permutations of a list where there might be duplicates.
uniquePerms :: (Eq a) => [a] -> [[a]]
uniquePerms = permBag . makeBag
-- | An unordered collection where duplicate values are allowed,
-- but represented with a single value and a count.
type Bag a = [(a, Int)]
makeBag :: (Eq a) => [a] -> Bag a
makeBag [] = []
makeBag (a:as) = mix a $ makeBag as
where
mix a [] = [(a,1)]
mix a (bn@(b,n):bs) | a == b = (b,n+1):bs
| otherwise = bn : mix a bs
permBag :: Bag a -> [[a]]
permBag [] = [[]]
permBag bs = concatMap (\(f,cs) -> map (f:) $ permBag cs) . oneOfEach $ bs
where
oneOfEach [] = []
oneOfEach (an@(a,n):bs) =
let bs' = if n == 1 then bs else (a,n-1):bs
in (a,bs') : mapSnd (an:) (oneOfEach bs)
apSnd f (a,b) = (a, f b)
mapSnd = map . apSnd
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
matchBrackets: true,
theme: "elegant"
});
</script>
<p><strong>MIME types defined:</strong> <code>text/x-haskell</code>.</p>
</body>
</html>
CodeMirror.defineMode("haxe", function(config, parserConfig) {
var indentUnit = config.indentUnit;
// Tokenizer
var keywords = function(){
function kw(type) {return {type: type, style: "keyword"};}
var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c");
var operator = kw("operator"), atom = {type: "atom", style: "atom"}, attribute = {type:"attribute", style: "attribute"};
var type = kw("typedef");
return {
"if": A, "while": A, "else": B, "do": B, "try": B,
"return": C, "break": C, "continue": C, "new": C, "throw": C,
"var": kw("var"), "inline":attribute, "static": attribute, "using":kw("import"),
"public": attribute, "private": attribute, "cast": kw("cast"), "import": kw("import"), "macro": kw("macro"),
"function": kw("function"), "catch": kw("catch"), "untyped": kw("untyped"), "callback": kw("cb"),
"for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"),
"in": operator, "never": kw("property_access"), "trace":kw("trace"),
"class": type, "enum":type, "interface":type, "typedef":type, "extends":type, "implements":type, "dynamic":type,
"true": atom, "false": atom, "null": atom
};
}();
var isOperatorChar = /[+\-*&%=<>!?|]/;
function chain(stream, state, f) {
state.tokenize = f;
return f(stream, state);
}
function nextUntilUnescaped(stream, end) {
var escaped = false, next;
while ((next = stream.next()) != null) {
if (next == end && !escaped)
return false;
escaped = !escaped && next == "\\";
}
return escaped;
}
// Used as scratch variables to communicate multiple values without
// consing up tons of objects.
var type, content;
function ret(tp, style, cont) {
type = tp; content = cont;
return style;
}
function haxeTokenBase(stream, state) {
var ch = stream.next();
if (ch == '"' || ch == "'")
return chain(stream, state, haxeTokenString(ch));
else if (/[\[\]{}\(\),;\:\.]/.test(ch))
return ret(ch);
else if (ch == "0" && stream.eat(/x/i)) {
stream.eatWhile(/[\da-f]/i);
return ret("number", "number");
}
else if (/\d/.test(ch) || ch == "-" && stream.eat(/\d/)) {
stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/);
return ret("number", "number");
}
else if (state.reAllowed && (ch == "~" && stream.eat(/\//))) {
nextUntilUnescaped(stream, "/");
stream.eatWhile(/[gimsu]/);
return ret("regexp", "string-2");
}
else if (ch == "/") {
if (stream.eat("*")) {
return chain(stream, state, haxeTokenComment);
}
else if (stream.eat("/")) {
stream.skipToEnd();
return ret("comment", "comment");
}
else {
stream.eatWhile(isOperatorChar);
return ret("operator", null, stream.current());
}
}
else if (ch == "#") {
stream.skipToEnd();
return ret("conditional", "meta");
}
else if (ch == "@") {
stream.eat(/:/);
stream.eatWhile(/[\w_]/);
return ret ("metadata", "meta");
}
else if (isOperatorChar.test(ch)) {
stream.eatWhile(isOperatorChar);
return ret("operator", null, stream.current());
}
else {
var word;
if(/[A-Z]/.test(ch))
{
stream.eatWhile(/[\w_<>]/);
word = stream.current();
return ret("type", "variable-3", word);
}
else
{
stream.eatWhile(/[\w_]/);
var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word];
return (known && state.kwAllowed) ? ret(known.type, known.style, word) :
ret("variable", "variable", word);
}
}
}
function haxeTokenString(quote) {
return function(stream, state) {
if (!nextUntilUnescaped(stream, quote))
state.tokenize = haxeTokenBase;
return ret("string", "string");
};
}
function haxeTokenComment(stream, state) {
var maybeEnd = false, ch;
while (ch = stream.next()) {
if (ch == "/" && maybeEnd) {
state.tokenize = haxeTokenBase;
break;
}
maybeEnd = (ch == "*");
}
return ret("comment", "comment");
}
// Parser
var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true};
function HaxeLexical(indented, column, type, align, prev, info) {
this.indented = indented;
this.column = column;
this.type = type;
this.prev = prev;
this.info = info;
if (align != null) this.align = align;
}
function inScope(state, varname) {
for (var v = state.localVars; v; v = v.next)
if (v.name == varname) return true;
}
function parseHaxe(state, style, type, content, stream) {
var cc = state.cc;
// Communicate our context to the combinators.
// (Less wasteful than consing up a hundred closures on every call.)
cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc;
if (!state.lexical.hasOwnProperty("align"))
state.lexical.align = true;
while(true) {
var combinator = cc.length ? cc.pop() : statement;
if (combinator(type, content)) {
while(cc.length && cc[cc.length - 1].lex)
cc.pop()();
if (cx.marked) return cx.marked;
if (type == "variable" && inScope(state, content)) return "variable-2";
if (type == "variable" && imported(state, content)) return "variable-3";
return style;
}
}
}
function imported(state, typename)
{
if (/[a-z]/.test(typename.charAt(0)))
return false;
var len = state.importedtypes.length;
for (var i = 0; i<len; i++)
if(state.importedtypes[i]==typename) return true;
}
function registerimport(importname) {
var state = cx.state;
for (var t = state.importedtypes; t; t = t.next)
if(t.name == importname) return;
state.importedtypes = { name: importname, next: state.importedtypes };
}
// Combinator utils
var cx = {state: null, column: null, marked: null, cc: null};
function pass() {
for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
}
function cont() {
pass.apply(null, arguments);
return true;
}
function register(varname) {
var state = cx.state;
if (state.context) {
cx.marked = "def";
for (var v = state.localVars; v; v = v.next)
if (v.name == varname) return;
state.localVars = {name: varname, next: state.localVars};
}
}
// Combinators
var defaultVars = {name: "this", next: null};
function pushcontext() {
if (!cx.state.context) cx.state.localVars = defaultVars;
cx.state.context = {prev: cx.state.context, vars: cx.state.localVars};
}
function popcontext() {
cx.state.localVars = cx.state.context.vars;
cx.state.context = cx.state.context.prev;
}
function pushlex(type, info) {
var result = function() {
var state = cx.state;
state.lexical = new HaxeLexical(state.indented, cx.stream.column(), type, null, state.lexical, info);
};
result.lex = true;
return result;
}
function poplex() {
var state = cx.state;
if (state.lexical.prev) {
if (state.lexical.type == ")")
state.indented = state.lexical.indented;
state.lexical = state.lexical.prev;
}
}
poplex.lex = true;
function expect(wanted) {
return function expecting(type) {
if (type == wanted) return cont();
else if (wanted == ";") return pass();
else return cont(arguments.callee);
};
}
function statement(type) {
if (type == "@") return cont(metadef);
if (type == "var") return cont(pushlex("vardef"), vardef1, expect(";"), poplex);
if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex);
if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
if (type == "{") return cont(pushlex("}"), pushcontext, block, poplex, popcontext);
if (type == ";") return cont();
if (type == "attribute") return cont(maybeattribute);
if (type == "function") return cont(functiondef);
if (type == "for") return cont(pushlex("form"), expect("("), pushlex(")"), forspec1, expect(")"),
poplex, statement, poplex);
if (type == "variable") return cont(pushlex("stat"), maybelabel);
if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"),
block, poplex, poplex);
if (type == "case") return cont(expression, expect(":"));
if (type == "default") return cont(expect(":"));
if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"),
statement, poplex, popcontext);
if (type == "import") return cont(importdef, expect(";"));
if (type == "typedef") return cont(typedef);
return pass(pushlex("stat"), expression, expect(";"), poplex);
}
function expression(type) {
if (atomicTypes.hasOwnProperty(type)) return cont(maybeoperator);
if (type == "function") return cont(functiondef);
if (type == "keyword c") return cont(maybeexpression);
if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeoperator);
if (type == "operator") return cont(expression);
if (type == "[") return cont(pushlex("]"), commasep(expression, "]"), poplex, maybeoperator);
if (type == "{") return cont(pushlex("}"), commasep(objprop, "}"), poplex, maybeoperator);
return cont();
}
function maybeexpression(type) {
if (type.match(/[;\}\)\],]/)) return pass();
return pass(expression);
}
function maybeoperator(type, value) {
if (type == "operator" && /\+\+|--/.test(value)) return cont(maybeoperator);
if (type == "operator" || type == ":") return cont(expression);
if (type == ";") return;
if (type == "(") return cont(pushlex(")"), commasep(expression, ")"), poplex, maybeoperator);
if (type == ".") return cont(property, maybeoperator);
if (type == "[") return cont(pushlex("]"), expression, expect("]"), poplex, maybeoperator);
}
function maybeattribute(type, value) {
if (type == "attribute") return cont(maybeattribute);
if (type == "function") return cont(functiondef);
if (type == "var") return cont(vardef1);
}
function metadef(type, value) {
if(type == ":") return cont(metadef);
if(type == "variable") return cont(metadef);
if(type == "(") return cont(pushlex(")"), comasep(metaargs, ")"), poplex, statement);
}
function metaargs(type, value) {
if(typ == "variable") return cont();
}
function importdef (type, value) {
if(type == "variable" && /[A-Z]/.test(value.charAt(0))) { registerimport(value); return cont(); }
else if(type == "variable" || type == "property" || type == ".") return cont(importdef);
}
function typedef (type, value)
{
if(type == "variable" && /[A-Z]/.test(value.charAt(0))) { registerimport(value); return cont(); }
}
function maybelabel(type) {
if (type == ":") return cont(poplex, statement);
return pass(maybeoperator, expect(";"), poplex);
}
function property(type) {
if (type == "variable") {cx.marked = "property"; return cont();}
}
function objprop(type) {
if (type == "variable") cx.marked = "property";
if (atomicTypes.hasOwnProperty(type)) return cont(expect(":"), expression);
}
function commasep(what, end) {
function proceed(type) {
if (type == ",") return cont(what, proceed);
if (type == end) return cont();
return cont(expect(end));
}
return function commaSeparated(type) {
if (type == end) return cont();
else return pass(what, proceed);
};
}
function block(type) {
if (type == "}") return cont();
return pass(statement, block);
}
function vardef1(type, value) {
if (type == "variable"){register(value); return cont(typeuse, vardef2);}
return cont();
}
function vardef2(type, value) {
if (value == "=") return cont(expression, vardef2);
if (type == ",") return cont(vardef1);
}
function forspec1(type, value) {
if (type == "variable") {
register(value);
}
return cont(pushlex(")"), pushcontext, forin, expression, poplex, statement, popcontext);
}
function forin(type, value) {
if (value == "in") return cont();
}
function functiondef(type, value) {
if (type == "variable") {register(value); return cont(functiondef);}
if (value == "new") return cont(functiondef);
if (type == "(") return cont(pushlex(")"), pushcontext, commasep(funarg, ")"), poplex, typeuse, statement, popcontext);
}
function typeuse(type, value) {
if(type == ":") return cont(typestring);
}
function typestring(type, value) {
if(type == "type") return cont();
if(type == "variable") return cont();
if(type == "{") return cont(pushlex("}"), commasep(typeprop, "}"), poplex);
}
function typeprop(type, value) {
if(type == "variable") return cont(typeuse);
}
function funarg(type, value) {
if (type == "variable") {register(value); return cont(typeuse);}
}
// Interface
return {
startState: function(basecolumn) {
var defaulttypes = ["Int", "Float", "String", "Void", "Std", "Bool", "Dynamic", "Array"];
return {
tokenize: haxeTokenBase,
reAllowed: true,
kwAllowed: true,
cc: [],
lexical: new HaxeLexical((basecolumn || 0) - indentUnit, 0, "block", false),
localVars: parserConfig.localVars,
importedtypes: defaulttypes,
context: parserConfig.localVars && {vars: parserConfig.localVars},
indented: 0
};
},
token: function(stream, state) {
if (stream.sol()) {
if (!state.lexical.hasOwnProperty("align"))
state.lexical.align = false;
state.indented = stream.indentation();
}
if (stream.eatSpace()) return null;
var style = state.tokenize(stream, state);
if (type == "comment") return style;
state.reAllowed = !!(type == "operator" || type == "keyword c" || type.match(/^[\[{}\(,;:]$/));
state.kwAllowed = type != '.';
return parseHaxe(state, style, type, content, stream);
},
indent: function(state, textAfter) {
if (state.tokenize != haxeTokenBase) return 0;
var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical;
if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev;
var type = lexical.type, closing = firstChar == type;
if (type == "vardef") return lexical.indented + 4;
else if (type == "form" && firstChar == "{") return lexical.indented;
else if (type == "stat" || type == "form") return lexical.indented + indentUnit;
else if (lexical.info == "switch" && !closing)
return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
else if (lexical.align) return lexical.column + (closing ? 0 : 1);
else return lexical.indented + (closing ? 0 : indentUnit);
},
electricChars: "{}"
};
});
CodeMirror.defineMIME("text/x-haxe", "haxe");
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Haxe mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="haxe.js"></script>
<link rel="stylesheet" href="../../doc/docs.css">
<style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
</head>
<body>
<h1>CodeMirror: Haxe mode</h1>
<div><textarea id="code" name="code">
import one.two.Three;
@attr("test")
class Foo&lt;T&gt; extends Three
{
public function new()
{
noFoo = 12;
}
public static inline function doFoo(obj:{k:Int, l:Float}):Int
{
for(i in 0...10)
{
obj.k++;
trace(i);
var var1 = new Array();
if(var1.length > 1)
throw "Error";
}
// The following line should not be colored, the variable is scoped out
var1;
/* Multi line
* Comment test
*/
return obj.k;
}
private function bar():Void
{
#if flash
var t1:String = "1.21";
#end
try {
doFoo({k:3, l:1.2});
}
catch (e : String) {
trace(e);
}
var t2:Float = cast(3.2);
var t3:haxe.Timer = new haxe.Timer();
var t4 = {k:Std.int(t2), l:Std.parseFloat(t1)};
var t5 = ~/123+.*$/i;
doFoo(t4);
untyped t1 = 4;
bob = new Foo&lt;Int&gt;
}
public var okFoo(default, never):Float;
var noFoo(getFoo, null):Int;
function getFoo():Int {
return noFoo;
}
public var three:Int;
}
enum Color
{
red;
green;
blue;
grey( v : Int );
rgb (r:Int,g:Int,b:Int);
}
</textarea></div>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
matchBrackets: true,
indentUnit: 4,
indentWithTabs: true
});
</script>
<p><strong>MIME types defined:</strong> <code>text/x-haxe</code>.</p>
</body>
</html>
CodeMirror.defineMode("htmlembedded", function(config, parserConfig) {
//config settings
var scriptStartRegex = parserConfig.scriptStartRegex || /^<%/i,
scriptEndRegex = parserConfig.scriptEndRegex || /^%>/i;
//inner modes
var scriptingMode, htmlMixedMode;
//tokenizer when in html mode
function htmlDispatch(stream, state) {
if (stream.match(scriptStartRegex, false)) {
state.token=scriptingDispatch;
return scriptingMode.token(stream, state.scriptState);
}
else
return htmlMixedMode.token(stream, state.htmlState);
}
//tokenizer when in scripting mode
function scriptingDispatch(stream, state) {
if (stream.match(scriptEndRegex, false)) {
state.token=htmlDispatch;
return htmlMixedMode.token(stream, state.htmlState);
}
else
return scriptingMode.token(stream, state.scriptState);
}
return {
startState: function() {
scriptingMode = scriptingMode || CodeMirror.getMode(config, parserConfig.scriptingModeSpec);
htmlMixedMode = htmlMixedMode || CodeMirror.getMode(config, "htmlmixed");
return {
token : parserConfig.startOpen ? scriptingDispatch : htmlDispatch,
htmlState : htmlMixedMode.startState(),
scriptState : scriptingMode.startState()
};
},
token: function(stream, state) {
return state.token(stream, state);
},
indent: function(state, textAfter) {
if (state.token == htmlDispatch)
return htmlMixedMode.indent(state.htmlState, textAfter);
else
return scriptingMode.indent(state.scriptState, textAfter);
},
copyState: function(state) {
return {
token : state.token,
htmlState : CodeMirror.copyState(htmlMixedMode, state.htmlState),
scriptState : CodeMirror.copyState(scriptingMode, state.scriptState)
};
},
electricChars: "/{}:",
innerMode: function(state) {
if (state.token == scriptingDispatch) return {state: state.scriptState, mode: scriptingMode};
else return {state: state.htmlState, mode: htmlMixedMode};
}
};
}, "htmlmixed");
CodeMirror.defineMIME("application/x-ejs", { name: "htmlembedded", scriptingModeSpec:"javascript"});
CodeMirror.defineMIME("application/x-aspx", { name: "htmlembedded", scriptingModeSpec:"text/x-csharp"});
CodeMirror.defineMIME("application/x-jsp", { name: "htmlembedded", scriptingModeSpec:"text/x-java"});
CodeMirror.defineMIME("application/x-erb", { name: "htmlembedded", scriptingModeSpec:"ruby"});
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Html Embedded Scripts mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="../xml/xml.js"></script>
<script src="../javascript/javascript.js"></script>
<script src="../css/css.js"></script>
<script src="../htmlmixed/htmlmixed.js"></script>
<script src="htmlembedded.js"></script>
<style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
<link rel="stylesheet" href="../../doc/docs.css">
</head>
<body>
<h1>CodeMirror: Html Embedded Scripts mode</h1>
<form><textarea id="code" name="code">
<%
function hello(who) {
return "Hello " + who;
}
%>
This is an example of EJS (embedded javascript)
<p>The program says <%= hello("world") %>.</p>
<script>
alert("And here is some normal JS code"); // also colored
</script>
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
matchBrackets: true,
mode: "application/x-ejs",
indentUnit: 4,
indentWithTabs: true,
enterMode: "keep",
tabMode: "shift"
});
</script>
<p>Mode for html embedded scripts like JSP and ASP.NET. Depends on HtmlMixed which in turn depends on
JavaScript, CSS and XML.<br />Other dependancies include those of the scriping language chosen.</p>
<p><strong>MIME types defined:</strong> <code>application/x-aspx</code> (ASP.NET),
<code>application/x-ejs</code> (Embedded Javascript), <code>application/x-jsp</code> (JavaServer Pages)</p>
</body>
</html>
CodeMirror.defineMode("htmlmixed", function(config) {
var htmlMode = CodeMirror.getMode(config, {name: "xml", htmlMode: true});
var jsMode = CodeMirror.getMode(config, "javascript");
var cssMode = CodeMirror.getMode(config, "css");
function html(stream, state) {
var style = htmlMode.token(stream, state.htmlState);
if (style == "tag" && stream.current() == ">" && state.htmlState.context) {
if (/^script$/i.test(state.htmlState.context.tagName)) {
state.token = javascript;
state.localState = jsMode.startState(htmlMode.indent(state.htmlState, ""));
}
else if (/^style$/i.test(state.htmlState.context.tagName)) {
state.token = css;
state.localState = cssMode.startState(htmlMode.indent(state.htmlState, ""));
}
}
return style;
}
function maybeBackup(stream, pat, style) {
var cur = stream.current();
var close = cur.search(pat), m;
if (close > -1) stream.backUp(cur.length - close);
else if (m = cur.match(/<\/?$/)) {
stream.backUp(cur[0].length);
if (!stream.match(pat, false)) stream.match(cur[0]);
}
return style;
}
function javascript(stream, state) {
if (stream.match(/^<\/\s*script\s*>/i, false)) {
state.token = html;
state.localState = null;
return html(stream, state);
}
return maybeBackup(stream, /<\/\s*script\s*>/,
jsMode.token(stream, state.localState));
}
function css(stream, state) {
if (stream.match(/^<\/\s*style\s*>/i, false)) {
state.token = html;
state.localState = null;
return html(stream, state);
}
return maybeBackup(stream, /<\/\s*style\s*>/,
cssMode.token(stream, state.localState));
}
return {
startState: function() {
var state = htmlMode.startState();
return {token: html, localState: null, mode: "html", htmlState: state};
},
copyState: function(state) {
if (state.localState)
var local = CodeMirror.copyState(state.token == css ? cssMode : jsMode, state.localState);
return {token: state.token, localState: local, mode: state.mode,
htmlState: CodeMirror.copyState(htmlMode, state.htmlState)};
},
token: function(stream, state) {
return state.token(stream, state);
},
indent: function(state, textAfter) {
if (state.token == html || /^\s*<\//.test(textAfter))
return htmlMode.indent(state.htmlState, textAfter);
else if (state.token == javascript)
return jsMode.indent(state.localState, textAfter);
else
return cssMode.indent(state.localState, textAfter);
},
electricChars: "/{}:",
innerMode: function(state) {
var mode = state.token == html ? htmlMode : state.token == javascript ? jsMode : cssMode;
return {state: state.localState || state.htmlState, mode: mode};
}
};
}, "xml", "javascript", "css");
CodeMirror.defineMIME("text/html", "htmlmixed");
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: HTML mixed mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="../xml/xml.js"></script>
<script src="../javascript/javascript.js"></script>
<script src="../css/css.js"></script>
<script src="htmlmixed.js"></script>
<link rel="stylesheet" href="../../doc/docs.css">
<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
</head>
<body>
<h1>CodeMirror: HTML mixed mode</h1>
<form><textarea id="code" name="code">
<html style="color: green">
<!-- this is a comment -->
<head>
<title>Mixed HTML Example</title>
<style type="text/css">
h1 {font-family: comic sans; color: #f0f;}
div {background: yellow !important;}
body {
max-width: 50em;
margin: 1em 2em 1em 5em;
}
</style>
</head>
<body>
<h1>Mixed HTML Example</h1>
<script>
function jsFunc(arg1, arg2) {
if (arg1 && arg2) document.body.innerHTML = "achoo";
}
</script>
</body>
</html>
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {mode: "text/html", tabMode: "indent"});
</script>
<p>The HTML mixed mode depends on the XML, JavaScript, and CSS modes.</p>
<p><strong>MIME types defined:</strong> <code>text/html</code>
(redefined, only takes effect if you load this parser after the
XML parser).</p>
</body>
</html>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: JavaScript mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="javascript.js"></script>
<link rel="stylesheet" href="../../doc/docs.css">
<style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
</head>
<body>
<h1>CodeMirror: JavaScript mode</h1>
<div><textarea id="code" name="code">
// Demo code (the actual new parser character stream implementation)
function StringStream(string) {
this.pos = 0;
this.string = string;
}
StringStream.prototype = {
done: function() {return this.pos >= this.string.length;},
peek: function() {return this.string.charAt(this.pos);},
next: function() {
if (this.pos &lt; this.string.length)
return this.string.charAt(this.pos++);
},
eat: function(match) {
var ch = this.string.charAt(this.pos);
if (typeof match == "string") var ok = ch == match;
else var ok = ch &amp;&amp; match.test ? match.test(ch) : match(ch);
if (ok) {this.pos++; return ch;}
},
eatWhile: function(match) {
var start = this.pos;
while (this.eat(match));
if (this.pos > start) return this.string.slice(start, this.pos);
},
backUp: function(n) {this.pos -= n;},
column: function() {return this.pos;},
eatSpace: function() {
var start = this.pos;
while (/\s/.test(this.string.charAt(this.pos))) this.pos++;
return this.pos - start;
},
match: function(pattern, consume, caseInsensitive) {
if (typeof pattern == "string") {
function cased(str) {return caseInsensitive ? str.toLowerCase() : str;}
if (cased(this.string).indexOf(cased(pattern), this.pos) == this.pos) {
if (consume !== false) this.pos += str.length;
return true;
}
}
else {
var match = this.string.slice(this.pos).match(pattern);
if (match &amp;&amp; consume !== false) this.pos += match[0].length;
return match;
}
}
};
</textarea></div>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
matchBrackets: true
});
</script>
<p>
JavaScript mode supports a two configuration
options:
<ul>
<li><code>json</code> which will set the mode to expect JSON data rather than a JavaScript program.</li>
<li>
<code>typescript</code> which will activate additional syntax highlighting and some other things for TypeScript code (<a href="typescript.html">demo</a>).
</li>
</ul>
</p>
<p><strong>MIME types defined:</strong> <code>text/javascript</code>, <code>application/json</code>, <code>text/typescript</code>, <code>application/typescript</code>.</p>
</body>
</html>
// TODO actually recognize syntax of TypeScript constructs
CodeMirror.defineMode("javascript", function(config, parserConfig) {
var indentUnit = config.indentUnit;
var jsonMode = parserConfig.json;
var isTS = parserConfig.typescript;
// Tokenizer
var keywords = function(){
function kw(type) {return {type: type, style: "keyword"};}
var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c");
var operator = kw("operator"), atom = {type: "atom", style: "atom"};
var jsKeywords = {
"if": A, "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B,
"return": C, "break": C, "continue": C, "new": C, "delete": C, "throw": C,
"var": kw("var"), "const": kw("var"), "let": kw("var"),
"function": kw("function"), "catch": kw("catch"),
"for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"),
"in": operator, "typeof": operator, "instanceof": operator,
"true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom
};
// Extend the 'normal' keywords with the TypeScript language extensions
if (isTS) {
var type = {type: "variable", style: "variable-3"};
var tsKeywords = {
// object-like things
"interface": kw("interface"),
"class": kw("class"),
"extends": kw("extends"),
"constructor": kw("constructor"),
// scope modifiers
"public": kw("public"),
"private": kw("private"),
"protected": kw("protected"),
"static": kw("static"),
"super": kw("super"),
// types
"string": type, "number": type, "bool": type, "any": type
};
for (var attr in tsKeywords) {
jsKeywords[attr] = tsKeywords[attr];
}
}
return jsKeywords;
}();
var isOperatorChar = /[+\-*&%=<>!?|]/;
function chain(stream, state, f) {
state.tokenize = f;
return f(stream, state);
}
function nextUntilUnescaped(stream, end) {
var escaped = false, next;
while ((next = stream.next()) != null) {
if (next == end && !escaped)
return false;
escaped = !escaped && next == "\\";
}
return escaped;
}
// Used as scratch variables to communicate multiple values without
// consing up tons of objects.
var type, content;
function ret(tp, style, cont) {
type = tp; content = cont;
return style;
}
function jsTokenBase(stream, state) {
var ch = stream.next();
if (ch == '"' || ch == "'")
return chain(stream, state, jsTokenString(ch));
else if (/[\[\]{}\(\),;\:\.]/.test(ch))
return ret(ch);
else if (ch == "0" && stream.eat(/x/i)) {
stream.eatWhile(/[\da-f]/i);
return ret("number", "number");
}
else if (/\d/.test(ch) || ch == "-" && stream.eat(/\d/)) {
stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/);
return ret("number", "number");
}
else if (ch == "/") {
if (stream.eat("*")) {
return chain(stream, state, jsTokenComment);
}
else if (stream.eat("/")) {
stream.skipToEnd();
return ret("comment", "comment");
}
else if (state.lastType == "operator" || state.lastType == "keyword c" ||
/^[\[{}\(,;:]$/.test(state.lastType)) {
nextUntilUnescaped(stream, "/");
stream.eatWhile(/[gimy]/); // 'y' is "sticky" option in Mozilla
return ret("regexp", "string-2");
}
else {
stream.eatWhile(isOperatorChar);
return ret("operator", null, stream.current());
}
}
else if (ch == "#") {
stream.skipToEnd();
return ret("error", "error");
}
else if (isOperatorChar.test(ch)) {
stream.eatWhile(isOperatorChar);
return ret("operator", null, stream.current());
}
else {
stream.eatWhile(/[\w\$_]/);
var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word];
return (known && state.lastType != ".") ? ret(known.type, known.style, word) :
ret("variable", "variable", word);
}
}
function jsTokenString(quote) {
return function(stream, state) {
if (!nextUntilUnescaped(stream, quote))
state.tokenize = jsTokenBase;
return ret("string", "string");
};
}
function jsTokenComment(stream, state) {
var maybeEnd = false, ch;
while (ch = stream.next()) {
if (ch == "/" && maybeEnd) {
state.tokenize = jsTokenBase;
break;
}
maybeEnd = (ch == "*");
}
return ret("comment", "comment");
}
// Parser
var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true};
function JSLexical(indented, column, type, align, prev, info) {
this.indented = indented;
this.column = column;
this.type = type;
this.prev = prev;
this.info = info;
if (align != null) this.align = align;
}
function inScope(state, varname) {
for (var v = state.localVars; v; v = v.next)
if (v.name == varname) return true;
}
function parseJS(state, style, type, content, stream) {
var cc = state.cc;
// Communicate our context to the combinators.
// (Less wasteful than consing up a hundred closures on every call.)
cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc;
if (!state.lexical.hasOwnProperty("align"))
state.lexical.align = true;
while(true) {
var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement;
if (combinator(type, content)) {
while(cc.length && cc[cc.length - 1].lex)
cc.pop()();
if (cx.marked) return cx.marked;
if (type == "variable" && inScope(state, content)) return "variable-2";
return style;
}
}
}
// Combinator utils
var cx = {state: null, column: null, marked: null, cc: null};
function pass() {
for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
}
function cont() {
pass.apply(null, arguments);
return true;
}
function register(varname) {
var state = cx.state;
if (state.context) {
cx.marked = "def";
for (var v = state.localVars; v; v = v.next)
if (v.name == varname) return;
state.localVars = {name: varname, next: state.localVars};
}
}
// Combinators
var defaultVars = {name: "this", next: {name: "arguments"}};
function pushcontext() {
cx.state.context = {prev: cx.state.context, vars: cx.state.localVars};
cx.state.localVars = defaultVars;
}
function popcontext() {
cx.state.localVars = cx.state.context.vars;
cx.state.context = cx.state.context.prev;
}
function pushlex(type, info) {
var result = function() {
var state = cx.state;
state.lexical = new JSLexical(state.indented, cx.stream.column(), type, null, state.lexical, info);
};
result.lex = true;
return result;
}
function poplex() {
var state = cx.state;
if (state.lexical.prev) {
if (state.lexical.type == ")")
state.indented = state.lexical.indented;
state.lexical = state.lexical.prev;
}
}
poplex.lex = true;
function expect(wanted) {
return function expecting(type) {
if (type == wanted) return cont();
else if (wanted == ";") return pass();
else return cont(arguments.callee);
};
}
function statement(type) {
if (type == "var") return cont(pushlex("vardef"), vardef1, expect(";"), poplex);
if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex);
if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
if (type == "{") return cont(pushlex("}"), block, poplex);
if (type == ";") return cont();
if (type == "function") return cont(functiondef);
if (type == "for") return cont(pushlex("form"), expect("("), pushlex(")"), forspec1, expect(")"),
poplex, statement, poplex);
if (type == "variable") return cont(pushlex("stat"), maybelabel);
if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"),
block, poplex, poplex);
if (type == "case") return cont(expression, expect(":"));
if (type == "default") return cont(expect(":"));
if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"),
statement, poplex, popcontext);
return pass(pushlex("stat"), expression, expect(";"), poplex);
}
function expression(type) {
if (atomicTypes.hasOwnProperty(type)) return cont(maybeoperator);
if (type == "function") return cont(functiondef);
if (type == "keyword c") return cont(maybeexpression);
if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeoperator);
if (type == "operator") return cont(expression);
if (type == "[") return cont(pushlex("]"), commasep(expression, "]"), poplex, maybeoperator);
if (type == "{") return cont(pushlex("}"), commasep(objprop, "}"), poplex, maybeoperator);
return cont();
}
function maybeexpression(type) {
if (type.match(/[;\}\)\],]/)) return pass();
return pass(expression);
}
function maybeoperator(type, value) {
if (type == "operator" && /\+\+|--/.test(value)) return cont(maybeoperator);
if (type == "operator" && value == "?") return cont(expression, expect(":"), expression);
if (type == ";") return;
if (type == "(") return cont(pushlex(")"), commasep(expression, ")"), poplex, maybeoperator);
if (type == ".") return cont(property, maybeoperator);
if (type == "[") return cont(pushlex("]"), expression, expect("]"), poplex, maybeoperator);
}
function maybelabel(type) {
if (type == ":") return cont(poplex, statement);
return pass(maybeoperator, expect(";"), poplex);
}
function property(type) {
if (type == "variable") {cx.marked = "property"; return cont();}
}
function objprop(type) {
if (type == "variable") cx.marked = "property";
if (atomicTypes.hasOwnProperty(type)) return cont(expect(":"), expression);
}
function commasep(what, end) {
function proceed(type) {
if (type == ",") return cont(what, proceed);
if (type == end) return cont();
return cont(expect(end));
}
return function commaSeparated(type) {
if (type == end) return cont();
else return pass(what, proceed);
};
}
function block(type) {
if (type == "}") return cont();
return pass(statement, block);
}
function maybetype(type) {
if (type == ":") return cont(typedef);
return pass();
}
function typedef(type) {
if (type == "variable"){cx.marked = "variable-3"; return cont();}
return pass();
}
function vardef1(type, value) {
if (type == "variable") {
register(value);
return isTS ? cont(maybetype, vardef2) : cont(vardef2);
}
return pass();
}
function vardef2(type, value) {
if (value == "=") return cont(expression, vardef2);
if (type == ",") return cont(vardef1);
}
function forspec1(type) {
if (type == "var") return cont(vardef1, expect(";"), forspec2);
if (type == ";") return cont(forspec2);
if (type == "variable") return cont(formaybein);
return cont(forspec2);
}
function formaybein(type, value) {
if (value == "in") return cont(expression);
return cont(maybeoperator, forspec2);
}
function forspec2(type, value) {
if (type == ";") return cont(forspec3);
if (value == "in") return cont(expression);
return cont(expression, expect(";"), forspec3);
}
function forspec3(type) {
if (type != ")") cont(expression);
}
function functiondef(type, value) {
if (type == "variable") {register(value); return cont(functiondef);}
if (type == "(") return cont(pushlex(")"), pushcontext, commasep(funarg, ")"), poplex, statement, popcontext);
}
function funarg(type, value) {
if (type == "variable") {register(value); return isTS ? cont(maybetype) : cont();}
}
// Interface
return {
startState: function(basecolumn) {
return {
tokenize: jsTokenBase,
lastType: null,
cc: [],
lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false),
localVars: parserConfig.localVars,
context: parserConfig.localVars && {vars: parserConfig.localVars},
indented: 0
};
},
token: function(stream, state) {
if (stream.sol()) {
if (!state.lexical.hasOwnProperty("align"))
state.lexical.align = false;
state.indented = stream.indentation();
}
if (stream.eatSpace()) return null;
var style = state.tokenize(stream, state);
if (type == "comment") return style;
state.lastType = type;
return parseJS(state, style, type, content, stream);
},
indent: function(state, textAfter) {
if (state.tokenize == jsTokenComment) return CodeMirror.Pass;
if (state.tokenize != jsTokenBase) return 0;
var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical;
if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev;
var type = lexical.type, closing = firstChar == type;
if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? 4 : 0);
else if (type == "form" && firstChar == "{") return lexical.indented;
else if (type == "form") return lexical.indented + indentUnit;
else if (type == "stat")
return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? indentUnit : 0);
else if (lexical.info == "switch" && !closing)
return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
else if (lexical.align) return lexical.column + (closing ? 0 : 1);
else return lexical.indented + (closing ? 0 : indentUnit);
},
electricChars: ":{}"
};
});
CodeMirror.defineMIME("text/javascript", "javascript");
CodeMirror.defineMIME("application/json", {name: "javascript", json: true});
CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true });
CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true });
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: TypeScript mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="javascript.js"></script>
<link rel="stylesheet" href="../../doc/docs.css">
<style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
</head>
<body>
<h1>CodeMirror: TypeScript mode</h1>
<div><textarea id="code" name="code">
class Greeter {
greeting: string;
constructor (message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
var greeter = new Greeter("world");
var button = document.createElement('button')
button.innerText = "Say Hello"
button.onclick = function() {
alert(greeter.greet())
}
document.body.appendChild(button)
</textarea></div>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
matchBrackets: true,
mode: "text/typescript"
});
</script>
<p>This is a specialization of the <a href="index.html">JavaScript mode</a>.</p>
</body>
</html>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Jinja2 mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="jinja2.js"></script>
<style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
<link rel="stylesheet" href="../../doc/docs.css">
</head>
<body>
<h1>CodeMirror: Jinja2 mode</h1>
<form><textarea id="code" name="code">
&lt;html style="color: green"&gt;
&lt;!-- this is a comment --&gt;
&lt;head&gt;
&lt;title&gt;Jinja2 Example&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;ul&gt;
{# this is a comment #}
{%- for item in li -%}
&lt;li&gt;
{{ item.label }}
&lt;/li&gt;
{% endfor -%}
&lt;/ul&gt;
&lt;/body&gt;
&lt;/html&gt;
</textarea></form>
<script>
var editor =
CodeMirror.fromTextArea(document.getElementById("code"), {mode:
{name: "jinja2", htmlMode: true}});
</script>
</body>
</html>
CodeMirror.defineMode("jinja2", function(config, parserConf) {
var keywords = ["block", "endblock", "for", "endfor", "in", "true", "false",
"loop", "none", "self", "super", "if", "as", "not", "and",
"else", "import", "with", "without", "context"];
keywords = new RegExp("^((" + keywords.join(")|(") + "))\\b");
function tokenBase (stream, state) {
var ch = stream.next();
if (ch == "{") {
if (ch = stream.eat(/\{|%|#/)) {
stream.eat("-");
state.tokenize = inTag(ch);
return "tag";
}
}
}
function inTag (close) {
if (close == "{") {
close = "}";
}
return function (stream, state) {
var ch = stream.next();
if ((ch == close || (ch == "-" && stream.eat(close)))
&& stream.eat("}")) {
state.tokenize = tokenBase;
return "tag";
}
if (stream.match(keywords)) {
return "keyword";
}
return close == "#" ? "comment" : "string";
};
}
return {
startState: function () {
return {tokenize: tokenBase};
},
token: function (stream, state) {
return state.tokenize(stream, state);
}
};
});
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: LESS mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="less.js"></script>
<style>.CodeMirror {background: #f8f8f8; border: 1px solid #ddd; font-size:12px} .CodeMirror-scroll {height: 400px}</style>
<link rel="stylesheet" href="../../doc/docs.css">
<link rel="stylesheet" href="../../theme/lesser-dark.css">
</head>
<body>
<h1>CodeMirror: LESS mode</h1>
<form><textarea id="code" name="code">@media screen and (device-aspect-ratio: 16/9) { … }
@media screen and (device-aspect-ratio: 32/18) { … }
@media screen and (device-aspect-ratio: 1280/720) { … }
@media screen and (device-aspect-ratio: 2560/1440) { … }
html:lang(fr-be)
html:lang(de)
:lang(fr-be) > q
:lang(de) > q
tr:nth-child(2n+1) /* represents every odd row of an HTML table */
tr:nth-child(odd) /* same */
tr:nth-child(2n+0) /* represents every even row of an HTML table */
tr:nth-child(even) /* same */
/* Alternate paragraph colours in CSS */
p:nth-child(4n+1) { color: navy; }
p:nth-child(4n+2) { color: green; }
p:nth-child(4n+3) { color: maroon; }
p:nth-child(4n+4) { color: purple; }
:nth-child(10n-1) /* represents the 9th, 19th, 29th, etc, element */
:nth-child(10n+9) /* Same */
:nth-child(10n+-1) /* Syntactically invalid, and would be ignored */
:nth-child( 3n + 1 )
:nth-child( +3n - 2 )
:nth-child( -n+ 6)
:nth-child( +6 )
html|tr:nth-child(-n+6) /* represents the 6 first rows of XHTML tables */
img:nth-of-type(2n+1) { float: right; }
img:nth-of-type(2n) { float: left; }
body > h2:nth-of-type(n+2):nth-last-of-type(n+2)
body > h2:not(:first-of-type):not(:last-of-type)
html|*:not(:link):not(:visited)
*|*:not(:hover)
p::first-line { text-transform: uppercase }
p { color: red; font-size: 12pt }
p::first-letter { color: green; font-size: 200% }
p::first-line { color: blue }
p { line-height: 1.1 }
p::first-letter { font-size: 3em; font-weight: normal }
span { font-weight: bold }
* /* a=0 b=0 c=0 -> specificity = 0 */
LI /* a=0 b=0 c=1 -> specificity = 1 */
UL LI /* a=0 b=0 c=2 -> specificity = 2 */
UL OL+LI /* a=0 b=0 c=3 -> specificity = 3 */
H1 + *[REL=up] /* a=0 b=1 c=1 -> specificity = 11 */
UL OL LI.red /* a=0 b=1 c=3 -> specificity = 13 */
LI.red.level /* a=0 b=2 c=1 -> specificity = 21 */
#x34y /* a=1 b=0 c=0 -> specificity = 100 */
#s12:not(FOO) /* a=1 b=0 c=1 -> specificity = 101 */
@namespace foo url(http://www.example.com);
foo|h1 { color: blue } /* first rule */
foo|* { color: yellow } /* second rule */
|h1 { color: red } /* ...*/
*|h1 { color: green }
h1 { color: green }
span[hello="Ocean"][goodbye="Land"]
a[rel~="copyright"] { ... }
a[href="http://www.w3.org/"] { ... }
DIALOGUE[character=romeo]
DIALOGUE[character=juliet]
[att^=val]
[att$=val]
[att*=val]
@namespace foo "http://www.example.com";
[foo|att=val] { color: blue }
[*|att] { color: yellow }
[|att] { color: green }
[att] { color: green }
*:target { color : red }
*:target::before { content : url(target.png) }
E[foo]{
padding:65px;
}
E[foo] ~ F{
padding:65px;
}
E#myid{
padding:65px;
}
input[type="search"]::-webkit-search-decoration,
input[type="search"]::-webkit-search-cancel-button {
-webkit-appearance: none; // Inner-padding issues in Chrome OSX, Safari 5
}
button::-moz-focus-inner,
input::-moz-focus-inner { // Inner padding and border oddities in FF3/4
padding: 0;
border: 0;
}
.btn {
// reset here as of 2.0.3 due to Recess property order
border-color: #ccc;
border-color: rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);
}
fieldset span button, fieldset span input[type="file"] {
font-size:12px;
font-family:Arial, Helvetica, sans-serif;
}
.el tr:nth-child(even):last-child td:first-child{
-moz-border-radius-bottomleft:3px;
-webkit-border-bottom-left-radius:3px;
border-bottom-left-radius:3px;
}
/* Some LESS code */
button {
width: 32px;
height: 32px;
border: 0;
margin: 4px;
cursor: pointer;
}
button.icon-plus { background: url(http://dahlström.net/tmp/sharp-icons/svg-icon-target.svg#plus) no-repeat; }
button.icon-chart { background: url(http://dahlström.net/tmp/sharp-icons/svg-icon-target.svg#chart) no-repeat; }
button:hover { background-color: #999; }
button:active { background-color: #666; }
@test_a: #eeeQQQ;//this is not a valid hex value and thus parsed as an element id
@test_b: #eeeFFF //this is a valid hex value but the declaration doesn't end with a semicolon and thus parsed as an element id
#eee aaa .box
{
#test bbb {
width: 500px;
height: 250px;
background-image: url(dir/output/sheep.png), url( betweengrassandsky.png );
background-position: center bottom, left top;
background-repeat: no-repeat;
}
}
@base: #f938ab;
.box-shadow(@style, @c) when (iscolor(@c)) {
box-shadow: @style @c;
-webkit-box-shadow: @style @c;
-moz-box-shadow: @style @c;
}
.box-shadow(@style, @alpha: 50%) when (isnumber(@alpha)) {
.box-shadow(@style, rgba(0, 0, 0, @alpha));
}
@color: #4D926F;
#header {
color: @color;
color: #000000;
}
h2 {
color: @color;
}
.rounded-corners (@radius: 5px) {
border-radius: @radius;
-webkit-border-radius: @radius;
-moz-border-radius: @radius;
}
#header {
.rounded-corners;
}
#footer {
.rounded-corners(10px);
}
.box-shadow (@x: 0, @y: 0, @blur: 1px, @alpha) {
@val: @x @y @blur rgba(0, 0, 0, @alpha);
box-shadow: @val;
-webkit-box-shadow: @val;
-moz-box-shadow: @val;
}
.box { @base: #f938ab;
color: saturate(@base, 5%);
border-color: lighten(@base, 30%);
div { .box-shadow(0, 0, 5px, 0.4) }
}
@import url("something.css");
@light-blue: hsl(190, 50%, 65%);
@light-yellow: desaturate(#fefec8, 10%);
@dark-yellow: desaturate(darken(@light-yellow, 10%), 40%);
@darkest: hsl(20, 0%, 15%);
@dark: hsl(190, 20%, 30%);
@medium: hsl(10, 60%, 30%);
@light: hsl(90, 40%, 20%);
@lightest: hsl(90, 20%, 90%);
@highlight: hsl(80, 50%, 90%);
@blue: hsl(210, 60%, 20%);
@alpha-blue: hsla(210, 60%, 40%, 0.5);
.box-shadow (@x, @y, @blur, @alpha) {
@value: @x @y @blur rgba(0, 0, 0, @alpha);
box-shadow: @value;
-moz-box-shadow: @value;
-webkit-box-shadow: @value;
}
.border-radius (@radius) {
border-radius: @radius;
-moz-border-radius: @radius;
-webkit-border-radius: @radius;
}
.border-radius (@radius, bottom) {
border-top-right-radius: 0;
border-top-left-radius: 0;
-moz-border-top-right-radius: 0;
-moz-border-top-left-radius: 0;
-webkit-border-top-left-radius: 0;
-webkit-border-top-right-radius: 0;
}
.border-radius (@radius, right) {
border-bottom-left-radius: 0;
border-top-left-radius: 0;
-moz-border-bottom-left-radius: 0;
-moz-border-top-left-radius: 0;
-webkit-border-bottom-left-radius: 0;
-webkit-border-top-left-radius: 0;
}
.box-shadow-inset (@x, @y, @blur, @color) {
box-shadow: @x @y @blur @color inset;
-moz-box-shadow: @x @y @blur @color inset;
-webkit-box-shadow: @x @y @blur @color inset;
}
.code () {
font-family: 'Bitstream Vera Sans Mono',
'DejaVu Sans Mono',
'Monaco',
Courier,
monospace !important;
}
.wrap () {
text-wrap: wrap;
white-space: pre-wrap; /* css-3 */
white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
word-wrap: break-word; /* Internet Explorer 5.5+ */
}
html { margin: 0 }
body {
background-color: @darkest;
margin: 0 auto;
font-family: Arial, sans-serif;
font-size: 100%;
overflow-x: hidden;
}
nav, header, footer, section, article {
display: block;
}
a {
color: #b83000;
}
h1 a {
color: black;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
h1, h2, h3, h4 {
margin: 0;
font-weight: normal;
}
ul, li {
list-style-type: none;
}
code { .code; }
code {
.string, .regexp { color: @dark }
.keyword { font-weight: bold }
.comment { color: rgba(0, 0, 0, 0.5) }
.number { color: @blue }
.class, .special { color: rgba(0, 50, 100, 0.8) }
}
pre {
padding: 0 30px;
.wrap;
}
blockquote {
font-style: italic;
}
body > footer {
text-align: left;
margin-left: 10px;
font-style: italic;
font-size: 18px;
color: #888;
}
#logo {
margin-top: 30px;
margin-bottom: 30px;
display: block;
width: 199px;
height: 81px;
background: url(/images/logo.png) no-repeat;
}
nav {
margin-left: 15px;
}
nav a, #dropdown li {
display: inline-block;
color: white;
line-height: 42px;
margin: 0;
padding: 0px 15px;
text-shadow: -1px -1px 1px rgba(0, 0, 0, 0.5);
text-decoration: none;
border: 2px solid transparent;
border-width: 0 2px;
&:hover {
.dark-red;
text-decoration: none;
}
}
.dark-red {
@red: @medium;
border: 2px solid darken(@red, 25%);
border-left-color: darken(@red, 15%);
border-right-color: darken(@red, 15%);
border-bottom: 0;
border-top: 0;
background-color: darken(@red, 10%);
}
.content {
margin: 0 auto;
width: 980px;
}
#menu {
position: absolute;
width: 100%;
z-index: 3;
clear: both;
display: block;
background-color: @blue;
height: 42px;
border-top: 2px solid lighten(@alpha-blue, 20%);
border-bottom: 2px solid darken(@alpha-blue, 25%);
.box-shadow(0, 1px, 8px, 0.6);
-moz-box-shadow: 0 0 0 #000; // Because firefox sucks.
&.docked {
background-color: hsla(210, 60%, 40%, 0.4);
}
&:hover {
background-color: @blue;
}
#dropdown {
margin: 0 0 0 117px;
padding: 0;
padding-top: 5px;
display: none;
width: 190px;
border-top: 2px solid @medium;
color: @highlight;
border: 2px solid darken(@medium, 25%);
border-left-color: darken(@medium, 15%);
border-right-color: darken(@medium, 15%);
border-top-width: 0;
background-color: darken(@medium, 10%);
ul {
padding: 0px;
}
li {
font-size: 14px;
display: block;
text-align: left;
padding: 0;
border: 0;
a {
display: block;
padding: 0px 15px;
text-decoration: none;
color: white;
&:hover {
background-color: darken(@medium, 15%);
text-decoration: none;
}
}
}
.border-radius(5px, bottom);
.box-shadow(0, 6px, 8px, 0.5);
}
}
#main {
margin: 0 auto;
width: 100%;
background-color: @light-blue;
border-top: 8px solid darken(@light-blue, 5%);
#intro {
background-color: lighten(@light-blue, 25%);
float: left;
margin-top: -8px;
margin-right: 5px;
height: 380px;
position: relative;
z-index: 2;
font-family: 'Droid Serif', 'Georgia';
width: 395px;
padding: 45px 20px 23px 30px;
border: 2px dashed darken(@light-blue, 10%);
.box-shadow(1px, 0px, 6px, 0.5);
border-bottom: 0;
border-top: 0;
#download { color: transparent; border: 0; float: left; display: inline-block; margin: 15px 0 15px -5px; }
#download img { display: inline-block}
#download-info {
code {
font-size: 13px;
}
color: @blue + #333; display: inline; float: left; margin: 36px 0 0 15px }
}
h2 {
span {
color: @medium;
}
color: @blue;
margin: 20px 0;
font-size: 24px;
line-height: 1.2em;
}
h3 {
color: @blue;
line-height: 1.4em;
margin: 30px 0 15px 0;
font-size: 1em;
text-shadow: 0px 0px 0px @lightest;
span { color: @medium }
}
#example {
p {
font-size: 18px;
color: @blue;
font-weight: bold;
text-shadow: 0px 1px 1px @lightest;
}
pre {
margin: 0;
text-shadow: 0 -1px 1px @darkest;
margin-top: 20px;
background-color: desaturate(@darkest, 8%);
border: 0;
width: 450px;
color: lighten(@lightest, 2%);
background-repeat: repeat;
padding: 15px;
border: 1px dashed @lightest;
line-height: 15px;
.box-shadow(0, 0px, 15px, 0.5);
.code;
.border-radius(2px);
code .attribute { color: hsl(40, 50%, 70%) }
code .variable { color: hsl(120, 10%, 50%) }
code .element { color: hsl(170, 20%, 50%) }
code .string, .regexp { color: hsl(75, 50%, 65%) }
code .class { color: hsl(40, 40%, 60%); font-weight: normal }
code .id { color: hsl(50, 40%, 60%); font-weight: normal }
code .comment { color: rgba(255, 255, 255, 0.2) }
code .number, .color { color: hsl(10, 40%, 50%) }
code .class, code .mixin, .special { color: hsl(190, 20%, 50%) }
#time { color: #aaa }
}
float: right;
font-size: 12px;
margin: 0;
margin-top: 15px;
padding: 0;
width: 500px;
}
}
.page {
.content {
width: 870px;
padding: 45px;
}
margin: 0 auto;
font-family: 'Georgia', serif;
font-size: 18px;
line-height: 26px;
padding: 0 60px;
code {
font-size: 16px;
}
pre {
border-width: 1px;
border-style: dashed;
padding: 15px;
margin: 15px 0;
}
h1 {
text-align: left;
font-size: 40px;
margin-top: 15px;
margin-bottom: 35px;
}
p + h1 { margin-top: 60px }
h2, h3 {
margin: 30px 0 15px 0;
}
p + h2, pre + h2, code + h2 {
border-top: 6px solid rgba(255, 255, 255, 0.1);
padding-top: 30px;
}
h3 {
margin: 15px 0;
}
}
#docs {
@bg: lighten(@light-blue, 5%);
border-top: 2px solid lighten(@bg, 5%);
color: @blue;
background-color: @light-blue;
.box-shadow(0, -2px, 5px, 0.2);
h1 {
font-family: 'Droid Serif', 'Georgia', serif;
padding-top: 30px;
padding-left: 45px;
font-size: 44px;
text-align: left;
margin: 30px 0 !important;
text-shadow: 0px 1px 1px @lightest;
font-weight: bold;
}
.content {
clear: both;
border-color: transparent;
background-color: lighten(@light-blue, 25%);
.box-shadow(0, 5px, 5px, 0.4);
}
pre {
@background: lighten(@bg, 30%);
color: lighten(@blue, 10%);
background-color: @background;
border-color: lighten(@light-blue, 25%);
border-width: 2px;
code .attribute { color: hsl(40, 50%, 30%) }
code .variable { color: hsl(120, 10%, 30%) }
code .element { color: hsl(170, 20%, 30%) }
code .string, .regexp { color: hsl(75, 50%, 35%) }
code .class { color: hsl(40, 40%, 30%); font-weight: normal }
code .id { color: hsl(50, 40%, 30%); font-weight: normal }
code .comment { color: rgba(0, 0, 0, 0.4) }
code .number, .color { color: hsl(10, 40%, 30%) }
code .class, code .mixin, .special { color: hsl(190, 20%, 30%) }
}
pre code { font-size: 15px }
p + h2, pre + h2, code + h2 { border-top-color: rgba(0, 0, 0, 0.1) }
}
td {
padding-right: 30px;
}
#synopsis {
.box-shadow(0, 5px, 5px, 0.2);
}
#synopsis, #about {
h2 {
font-size: 30px;
padding: 10px 0;
}
h1 + h2 {
margin-top: 15px;
}
h3 { font-size: 22px }
.code-example {
border-spacing: 0;
border-width: 1px;
border-style: dashed;
padding: 0;
pre { border: 0; margin: 0 }
td {
border: 0;
margin: 0;
background-color: desaturate(darken(@darkest, 5%), 20%);
vertical-align: top;
padding: 0;
}
tr { padding: 0 }
}
.css-output {
td {
border-left: 0;
}
}
.less-example {
//border-right: 1px dotted rgba(255, 255, 255, 0.5) !important;
}
.css-output, .less-example {
width: 390px;
}
pre {
padding: 20px;
line-height: 20px;
font-size: 14px;
}
}
#about, #synopsis, #guide {
a {
text-decoration: none;
color: @light-yellow;
border-bottom: 1px dashed rgba(255, 255, 255, 0.2);
&:hover {
text-decoration: none;
border-bottom: 1px dashed @light-yellow;
}
}
@bg: desaturate(darken(@darkest, 5%), 20%);
text-shadow: 0 -1px 1px lighten(@bg, 5%);
color: @highlight;
background-color: @bg;
.content {
background-color: desaturate(@darkest, 20%);
clear: both;
.box-shadow(0, 5px, 5px, 0.4);
}
h1, h2, h3 {
color: @dark-yellow;
}
pre {
code .attribute { color: hsl(40, 50%, 70%) }
code .variable { color: hsl(120, 10%, 50%) }
code .element { color: hsl(170, 20%, 50%) }
code .string, .regexp { color: hsl(75, 50%, 65%) }
code .class { color: hsl(40, 40%, 60%); font-weight: normal }
code .id { color: hsl(50, 40%, 60%); font-weight: normal }
code .comment { color: rgba(255, 255, 255, 0.2) }
code .number, .color { color: hsl(10, 40%, 50%) }
code .class, code .mixin, .special { color: hsl(190, 20%, 50%) }
background-color: @bg;
border-color: darken(@light-yellow, 5%);
}
code {
color: darken(@dark-yellow, 5%);
.string, .regexp { color: desaturate(@light-blue, 15%) }
.keyword { color: hsl(40, 40%, 60%); font-weight: normal }
.comment { color: rgba(255, 255, 255, 0.2) }
.number { color: lighten(@blue, 10%) }
.class, .special { color: hsl(190, 20%, 50%) }
}
}
#guide {
background-color: @darkest;
.content {
background-color: transparent;
}
}
#about {
background-color: @darkest !important;
.content {
background-color: desaturate(lighten(@darkest, 3%), 5%);
}
}
#synopsis {
background-color: desaturate(lighten(@darkest, 3%), 5%) !important;
.content {
background-color: desaturate(lighten(@darkest, 3%), 5%);
}
pre {}
}
#synopsis, #guide {
.content {
.box-shadow(0, 0px, 0px, 0.0);
}
}
#about footer {
margin-top: 30px;
padding-top: 30px;
border-top: 6px solid rgba(0, 0, 0, 0.1);
text-align: center;
font-size: 16px;
color: rgba(255, 255, 255, 0.35);
#copy { font-size: 12px }
text-shadow: -1px -1px 1px rgba(0, 0, 0, 0.02);
}
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
theme: "lesser-dark",
lineNumbers : true,
matchBrackets : true
});
</script>
<p><strong>MIME types defined:</strong> <code>text/x-less</code>, <code>text/css</code> (if not previously defined).</p>
</body>
</html>
/*
LESS mode - http://www.lesscss.org/
Ported to CodeMirror by Peter Kroon <plakroon@gmail.com>
Report bugs/issues here: https://github.com/marijnh/CodeMirror/issues GitHub: @peterkroon
*/
CodeMirror.defineMode("less", function(config) {
var indentUnit = config.indentUnit, type;
function ret(style, tp) {type = tp; return style;}
//html tags
var tags = "a abbr acronym address applet area article aside audio b base basefont bdi bdo big blockquote body br button canvas caption cite code col colgroup command datalist dd del details dfn dir div dl dt em embed fieldset figcaption figure font footer form frame frameset h1 h2 h3 h4 h5 h6 head header hgroup hr html i iframe img input ins keygen kbd label legend li link map mark menu meta meter nav noframes noscript object ol optgroup option output p param pre progress q rp rt ruby s samp script section select small source span strike strong style sub summary sup table tbody td textarea tfoot th thead time title tr track tt u ul var video wbr".split(' ');
function inTagsArray(val){
for(var i=0; i<tags.length; i++)if(val === tags[i])return true;
}
var selectors = /(^\:root$|^\:nth\-child$|^\:nth\-last\-child$|^\:nth\-of\-type$|^\:nth\-last\-of\-type$|^\:first\-child$|^\:last\-child$|^\:first\-of\-type$|^\:last\-of\-type$|^\:only\-child$|^\:only\-of\-type$|^\:empty$|^\:link|^\:visited$|^\:active$|^\:hover$|^\:focus$|^\:target$|^\:lang$|^\:enabled^\:disabled$|^\:checked$|^\:first\-line$|^\:first\-letter$|^\:before$|^\:after$|^\:not$|^\:required$|^\:invalid$)/;
function tokenBase(stream, state) {
var ch = stream.next();
if (ch == "@") {stream.eatWhile(/[\w\-]/); return ret("meta", stream.current());}
else if (ch == "/" && stream.eat("*")) {
state.tokenize = tokenCComment;
return tokenCComment(stream, state);
}
else if (ch == "<" && stream.eat("!")) {
state.tokenize = tokenSGMLComment;
return tokenSGMLComment(stream, state);
}
else if (ch == "=") ret(null, "compare");
else if (ch == "|" && stream.eat("=")) return ret(null, "compare");
else if (ch == "\"" || ch == "'") {
state.tokenize = tokenString(ch);
return state.tokenize(stream, state);
}
else if (ch == "/") { // e.g.: .png will not be parsed as a class
if(stream.eat("/")){
state.tokenize = tokenSComment;
return tokenSComment(stream, state);
}else{
if(type == "string" || type == "(")return ret("string", "string");
if(state.stack[state.stack.length-1] != undefined)return ret(null, ch);
stream.eatWhile(/[\a-zA-Z0-9\-_.\s]/);
if( /\/|\)|#/.test(stream.peek() || (stream.eatSpace() && stream.peek() == ")")) || stream.eol() )return ret("string", "string"); // let url(/images/logo.png) without quotes return as string
}
}
else if (ch == "!") {
stream.match(/^\s*\w*/);
return ret("keyword", "important");
}
else if (/\d/.test(ch)) {
stream.eatWhile(/[\w.%]/);
return ret("number", "unit");
}
else if (/[,+<>*\/]/.test(ch)) {
if(stream.peek() == "=" || type == "a")return ret("string", "string");
return ret(null, "select-op");
}
else if (/[;{}:\[\]()~\|]/.test(ch)) {
if(ch == ":"){
stream.eatWhile(/[a-z\\\-]/);
if( selectors.test(stream.current()) ){
return ret("tag", "tag");
}else if(stream.peek() == ":"){//::-webkit-search-decoration
stream.next();
stream.eatWhile(/[a-z\\\-]/);
if(stream.current().match(/\:\:\-(o|ms|moz|webkit)\-/))return ret("string", "string");
if( selectors.test(stream.current().substring(1)) )return ret("tag", "tag");
return ret(null, ch);
}else{
return ret(null, ch);
}
}else if(ch == "~"){
if(type == "r")return ret("string", "string");
}else{
return ret(null, ch);
}
}
else if (ch == ".") {
if(type == "(" || type == "string")return ret("string", "string"); // allow url(../image.png)
stream.eatWhile(/[\a-zA-Z0-9\-_]/);
if(stream.peek() == " ")stream.eatSpace();
if(stream.peek() == ")")return ret("number", "unit");//rgba(0,0,0,.25);
return ret("tag", "tag");
}
else if (ch == "#") {
//we don't eat white-space, we want the hex color and or id only
stream.eatWhile(/[A-Za-z0-9]/);
//check if there is a proper hex color length e.g. #eee || #eeeEEE
if(stream.current().length == 4 || stream.current().length == 7){
if(stream.current().match(/[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3}/,false) != null){//is there a valid hex color value present in the current stream
//when not a valid hex value, parse as id
if(stream.current().substring(1) != stream.current().match(/[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3}/,false))return ret("atom", "tag");
//eat white-space
stream.eatSpace();
//when hex value declaration doesn't end with [;,] but is does with a slash/cc comment treat it as an id, just like the other hex values that don't end with[;,]
if( /[\/<>.(){!$%^&*_\-\\?=+\|#'~`]/.test(stream.peek()) )return ret("atom", "tag");
//#time { color: #aaa }
else if(stream.peek() == "}" )return ret("number", "unit");
//we have a valid hex color value, parse as id whenever an element/class is defined after the hex(id) value e.g. #eee aaa || #eee .aaa
else if( /[a-zA-Z\\]/.test(stream.peek()) )return ret("atom", "tag");
//when a hex value is on the end of a line, parse as id
else if(stream.eol())return ret("atom", "tag");
//default
else return ret("number", "unit");
}else{//when not a valid hexvalue in the current stream e.g. #footer
stream.eatWhile(/[\w\\\-]/);
return ret("atom", "tag");
}
}else{//when not a valid hexvalue length
stream.eatWhile(/[\w\\\-]/);
return ret("atom", "tag");
}
}
else if (ch == "&") {
stream.eatWhile(/[\w\-]/);
return ret(null, ch);
}
else {
stream.eatWhile(/[\w\\\-_%.{]/);
if(type == "string"){
return ret("string", "string");
}else if(stream.current().match(/(^http$|^https$)/) != null){
stream.eatWhile(/[\w\\\-_%.{:\/]/);
return ret("string", "string");
}else if(stream.peek() == "<" || stream.peek() == ">"){
return ret("tag", "tag");
}else if( /\(/.test(stream.peek()) ){
return ret(null, ch);
}else if (stream.peek() == "/" && state.stack[state.stack.length-1] != undefined){ // url(dir/center/image.png)
return ret("string", "string");
}else if( stream.current().match(/\-\d|\-.\d/) ){ // match e.g.: -5px -0.4 etc... only colorize the minus sign
//commment out these 2 comment if you want the minus sign to be parsed as null -500px
//stream.backUp(stream.current().length-1);
//return ret(null, ch); //console.log( stream.current() );
return ret("number", "unit");
}else if( inTagsArray(stream.current().toLowerCase()) ){ // match html tags
return ret("tag", "tag");
}else if( /\/|[\s\)]/.test(stream.peek() || stream.eol() || (stream.eatSpace() && stream.peek() == "/")) && stream.current().indexOf(".") !== -1){
if(stream.current().substring(stream.current().length-1,stream.current().length) == "{"){
stream.backUp(1);
return ret("tag", "tag");
}//end if
stream.eatSpace();
if( /[{<>.a-zA-Z\/]/.test(stream.peek()) || stream.eol() )return ret("tag", "tag"); // e.g. button.icon-plus
return ret("string", "string"); // let url(/images/logo.png) without quotes return as string
}else if( stream.eol() || stream.peek() == "[" || stream.peek() == "#" || type == "tag" ){
if(stream.current().substring(stream.current().length-1,stream.current().length) == "{")stream.backUp(1);
return ret("tag", "tag");
}else if(type == "compare" || type == "a" || type == "("){
return ret("string", "string");
}else if(type == "|" || stream.current() == "-" || type == "["){
return ret(null, ch);
}else if(stream.peek() == ":") {
stream.next();
var t_v = stream.peek() == ":" ? true : false;
if(!t_v){
var old_pos = stream.pos;
var sc = stream.current().length;
stream.eatWhile(/[a-z\\\-]/);
var new_pos = stream.pos;
if(stream.current().substring(sc-1).match(selectors) != null){
stream.backUp(new_pos-(old_pos-1));
return ret("tag", "tag");
} else stream.backUp(new_pos-(old_pos-1));
}else{
stream.backUp(1);
}
if(t_v)return ret("tag", "tag"); else return ret("variable", "variable");
}else{
return ret("variable", "variable");
}
}
}
function tokenSComment(stream, state) { // SComment = Slash comment
stream.skipToEnd();
state.tokenize = tokenBase;
return ret("comment", "comment");
}
function tokenCComment(stream, state) {
var maybeEnd = false, ch;
while ((ch = stream.next()) != null) {
if (maybeEnd && ch == "/") {
state.tokenize = tokenBase;
break;
}
maybeEnd = (ch == "*");
}
return ret("comment", "comment");
}
function tokenSGMLComment(stream, state) {
var dashes = 0, ch;
while ((ch = stream.next()) != null) {
if (dashes >= 2 && ch == ">") {
state.tokenize = tokenBase;
break;
}
dashes = (ch == "-") ? dashes + 1 : 0;
}
return ret("comment", "comment");
}
function tokenString(quote) {
return function(stream, state) {
var escaped = false, ch;
while ((ch = stream.next()) != null) {
if (ch == quote && !escaped)
break;
escaped = !escaped && ch == "\\";
}
if (!escaped) state.tokenize = tokenBase;
return ret("string", "string");
};
}
return {
startState: function(base) {
return {tokenize: tokenBase,
baseIndent: base || 0,
stack: []};
},
token: function(stream, state) {
if (stream.eatSpace()) return null;
var style = state.tokenize(stream, state);
var context = state.stack[state.stack.length-1];
if (type == "hash" && context == "rule") style = "atom";
else if (style == "variable") {
if (context == "rule") style = null; //"tag"
else if (!context || context == "@media{") {
style = stream.current() == "when" ? "variable" :
/[\s,|\s\)|\s]/.test(stream.peek()) ? "tag" : type;
}
}
if (context == "rule" && /^[\{\};]$/.test(type))
state.stack.pop();
if (type == "{") {
if (context == "@media") state.stack[state.stack.length-1] = "@media{";
else state.stack.push("{");
}
else if (type == "}") state.stack.pop();
else if (type == "@media") state.stack.push("@media");
else if (context == "{" && type != "comment") state.stack.push("rule");
return style;
},
indent: function(state, textAfter) {
var n = state.stack.length;
if (/^\}/.test(textAfter))
n -= state.stack[state.stack.length-1] == "rule" ? 2 : 1;
return state.baseIndent + n * indentUnit;
},
electricChars: "}"
};
});
CodeMirror.defineMIME("text/x-less", "less");
if (!CodeMirror.mimeModes.hasOwnProperty("text/css"))
CodeMirror.defineMIME("text/css", "less");
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Lua mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="lua.js"></script>
<link rel="stylesheet" href="../../theme/neat.css">
<style>.CodeMirror {border: 1px solid black;}</style>
<link rel="stylesheet" href="../../doc/docs.css">
</head>
<body>
<h1>CodeMirror: Lua mode</h1>
<form><textarea id="code" name="code">
--[[
example useless code to show lua syntax highlighting
this is multiline comment
]]
function blahblahblah(x)
local table = {
"asd" = 123,
"x" = 0.34,
}
if x ~= 3 then
print( x )
elseif x == "string"
my_custom_function( 0x34 )
else
unknown_function( "some string" )
end
--single line comment
end
function blablabla3()
for k,v in ipairs( table ) do
--abcde..
y=[=[
x=[[
x is a multi line string
]]
but its definition is iside a highest level string!
]=]
print(" \"\" ")
s = math.sin( x )
end
end
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
tabMode: "indent",
matchBrackets: true,
theme: "neat"
});
</script>
<p>Loosely based on Franciszek
Wawrzak's <a href="http://codemirror.net/1/contrib/lua">CodeMirror
1 mode</a>. One configuration parameter is
supported, <code>specials</code>, to which you can provide an
array of strings to have those identifiers highlighted with
the <code>lua-special</code> style.</p>
<p><strong>MIME types defined:</strong> <code>text/x-lua</code>.</p>
</body>
</html>
// LUA mode. Ported to CodeMirror 2 from Franciszek Wawrzak's
// CodeMirror 1 mode.
// highlights keywords, strings, comments (no leveling supported! ("[==[")), tokens, basic indenting
CodeMirror.defineMode("lua", function(config, parserConfig) {
var indentUnit = config.indentUnit;
function prefixRE(words) {
return new RegExp("^(?:" + words.join("|") + ")", "i");
}
function wordRE(words) {
return new RegExp("^(?:" + words.join("|") + ")$", "i");
}
var specials = wordRE(parserConfig.specials || []);
// long list of standard functions from lua manual
var builtins = wordRE([
"_G","_VERSION","assert","collectgarbage","dofile","error","getfenv","getmetatable","ipairs","load",
"loadfile","loadstring","module","next","pairs","pcall","print","rawequal","rawget","rawset","require",
"select","setfenv","setmetatable","tonumber","tostring","type","unpack","xpcall",
"coroutine.create","coroutine.resume","coroutine.running","coroutine.status","coroutine.wrap","coroutine.yield",
"debug.debug","debug.getfenv","debug.gethook","debug.getinfo","debug.getlocal","debug.getmetatable",
"debug.getregistry","debug.getupvalue","debug.setfenv","debug.sethook","debug.setlocal","debug.setmetatable",
"debug.setupvalue","debug.traceback",
"close","flush","lines","read","seek","setvbuf","write",
"io.close","io.flush","io.input","io.lines","io.open","io.output","io.popen","io.read","io.stderr","io.stdin",
"io.stdout","io.tmpfile","io.type","io.write",
"math.abs","math.acos","math.asin","math.atan","math.atan2","math.ceil","math.cos","math.cosh","math.deg",
"math.exp","math.floor","math.fmod","math.frexp","math.huge","math.ldexp","math.log","math.log10","math.max",
"math.min","math.modf","math.pi","math.pow","math.rad","math.random","math.randomseed","math.sin","math.sinh",
"math.sqrt","math.tan","math.tanh",
"os.clock","os.date","os.difftime","os.execute","os.exit","os.getenv","os.remove","os.rename","os.setlocale",
"os.time","os.tmpname",
"package.cpath","package.loaded","package.loaders","package.loadlib","package.path","package.preload",
"package.seeall",
"string.byte","string.char","string.dump","string.find","string.format","string.gmatch","string.gsub",
"string.len","string.lower","string.match","string.rep","string.reverse","string.sub","string.upper",
"table.concat","table.insert","table.maxn","table.remove","table.sort"
]);
var keywords = wordRE(["and","break","elseif","false","nil","not","or","return",
"true","function", "end", "if", "then", "else", "do",
"while", "repeat", "until", "for", "in", "local" ]);
var indentTokens = wordRE(["function", "if","repeat","do", "\\(", "{"]);
var dedentTokens = wordRE(["end", "until", "\\)", "}"]);
var dedentPartial = prefixRE(["end", "until", "\\)", "}", "else", "elseif"]);
function readBracket(stream) {
var level = 0;
while (stream.eat("=")) ++level;
stream.eat("[");
return level;
}
function normal(stream, state) {
var ch = stream.next();
if (ch == "-" && stream.eat("-")) {
if (stream.eat("[") && stream.eat("["))
return (state.cur = bracketed(readBracket(stream), "comment"))(stream, state);
stream.skipToEnd();
return "comment";
}
if (ch == "\"" || ch == "'")
return (state.cur = string(ch))(stream, state);
if (ch == "[" && /[\[=]/.test(stream.peek()))
return (state.cur = bracketed(readBracket(stream), "string"))(stream, state);
if (/\d/.test(ch)) {
stream.eatWhile(/[\w.%]/);
return "number";
}
if (/[\w_]/.test(ch)) {
stream.eatWhile(/[\w\\\-_.]/);
return "variable";
}
return null;
}
function bracketed(level, style) {
return function(stream, state) {
var curlev = null, ch;
while ((ch = stream.next()) != null) {
if (curlev == null) {if (ch == "]") curlev = 0;}
else if (ch == "=") ++curlev;
else if (ch == "]" && curlev == level) { state.cur = normal; break; }
else curlev = null;
}
return style;
};
}
function string(quote) {
return function(stream, state) {
var escaped = false, ch;
while ((ch = stream.next()) != null) {
if (ch == quote && !escaped) break;
escaped = !escaped && ch == "\\";
}
if (!escaped) state.cur = normal;
return "string";
};
}
return {
startState: function(basecol) {
return {basecol: basecol || 0, indentDepth: 0, cur: normal};
},
token: function(stream, state) {
if (stream.eatSpace()) return null;
var style = state.cur(stream, state);
var word = stream.current();
if (style == "variable") {
if (keywords.test(word)) style = "keyword";
else if (builtins.test(word)) style = "builtin";
else if (specials.test(word)) style = "variable-2";
}
if ((style != "comment") && (style != "string")){
if (indentTokens.test(word)) ++state.indentDepth;
else if (dedentTokens.test(word)) --state.indentDepth;
}
return style;
},
indent: function(state, textAfter) {
var closing = dedentPartial.test(textAfter);
return state.basecol + indentUnit * (state.indentDepth - (closing ? 1 : 0));
}
};
});
CodeMirror.defineMIME("text/x-lua", "lua");
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Markdown mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="../xml/xml.js"></script>
<script src="markdown.js"></script>
<style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
<link rel="stylesheet" href="../../doc/docs.css">
</head>
<body>
<h1>CodeMirror: Markdown mode</h1>
<!-- source: http://daringfireball.net/projects/markdown/basics.text -->
<form><textarea id="code" name="code">
Markdown: Basics
================
&lt;ul id="ProjectSubmenu"&gt;
&lt;li&gt;&lt;a href="/projects/markdown/" title="Markdown Project Page"&gt;Main&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a class="selected" title="Markdown Basics"&gt;Basics&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="/projects/markdown/syntax" title="Markdown Syntax Documentation"&gt;Syntax&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="/projects/markdown/license" title="Pricing and License Information"&gt;License&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="/projects/markdown/dingus" title="Online Markdown Web Form"&gt;Dingus&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
Getting the Gist of Markdown's Formatting Syntax
------------------------------------------------
This page offers a brief overview of what it's like to use Markdown.
The [syntax page] [s] provides complete, detailed documentation for
every feature, but Markdown should be very easy to pick up simply by
looking at a few examples of it in action. The examples on this page
are written in a before/after style, showing example syntax and the
HTML output produced by Markdown.
It's also helpful to simply try Markdown out; the [Dingus] [d] is a
web application that allows you type your own Markdown-formatted text
and translate it to XHTML.
**Note:** This document is itself written using Markdown; you
can [see the source for it by adding '.text' to the URL] [src].
[s]: /projects/markdown/syntax "Markdown Syntax"
[d]: /projects/markdown/dingus "Markdown Dingus"
[src]: /projects/markdown/basics.text
## Paragraphs, Headers, Blockquotes ##
A paragraph is simply one or more consecutive lines of text, separated
by one or more blank lines. (A blank line is any line that looks like
a blank line -- a line containing nothing but spaces or tabs is
considered blank.) Normal paragraphs should not be indented with
spaces or tabs.
Markdown offers two styles of headers: *Setext* and *atx*.
Setext-style headers for `&lt;h1&gt;` and `&lt;h2&gt;` are created by
"underlining" with equal signs (`=`) and hyphens (`-`), respectively.
To create an atx-style header, you put 1-6 hash marks (`#`) at the
beginning of the line -- the number of hashes equals the resulting
HTML header level.
Blockquotes are indicated using email-style '`&gt;`' angle brackets.
Markdown:
A First Level Header
====================
A Second Level Header
---------------------
Now is the time for all good men to come to
the aid of their country. This is just a
regular paragraph.
The quick brown fox jumped over the lazy
dog's back.
### Header 3
&gt; This is a blockquote.
&gt;
&gt; This is the second paragraph in the blockquote.
&gt;
&gt; ## This is an H2 in a blockquote
Output:
&lt;h1&gt;A First Level Header&lt;/h1&gt;
&lt;h2&gt;A Second Level Header&lt;/h2&gt;
&lt;p&gt;Now is the time for all good men to come to
the aid of their country. This is just a
regular paragraph.&lt;/p&gt;
&lt;p&gt;The quick brown fox jumped over the lazy
dog's back.&lt;/p&gt;
&lt;h3&gt;Header 3&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;This is a blockquote.&lt;/p&gt;
&lt;p&gt;This is the second paragraph in the blockquote.&lt;/p&gt;
&lt;h2&gt;This is an H2 in a blockquote&lt;/h2&gt;
&lt;/blockquote&gt;
### Phrase Emphasis ###
Markdown uses asterisks and underscores to indicate spans of emphasis.
Markdown:
Some of these words *are emphasized*.
Some of these words _are emphasized also_.
Use two asterisks for **strong emphasis**.
Or, if you prefer, __use two underscores instead__.
Output:
&lt;p&gt;Some of these words &lt;em&gt;are emphasized&lt;/em&gt;.
Some of these words &lt;em&gt;are emphasized also&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;Use two asterisks for &lt;strong&gt;strong emphasis&lt;/strong&gt;.
Or, if you prefer, &lt;strong&gt;use two underscores instead&lt;/strong&gt;.&lt;/p&gt;
## Lists ##
Unordered (bulleted) lists use asterisks, pluses, and hyphens (`*`,
`+`, and `-`) as list markers. These three markers are
interchangable; this:
* Candy.
* Gum.
* Booze.
this:
+ Candy.
+ Gum.
+ Booze.
and this:
- Candy.
- Gum.
- Booze.
all produce the same output:
&lt;ul&gt;
&lt;li&gt;Candy.&lt;/li&gt;
&lt;li&gt;Gum.&lt;/li&gt;
&lt;li&gt;Booze.&lt;/li&gt;
&lt;/ul&gt;
Ordered (numbered) lists use regular numbers, followed by periods, as
list markers:
1. Red
2. Green
3. Blue
Output:
&lt;ol&gt;
&lt;li&gt;Red&lt;/li&gt;
&lt;li&gt;Green&lt;/li&gt;
&lt;li&gt;Blue&lt;/li&gt;
&lt;/ol&gt;
If you put blank lines between items, you'll get `&lt;p&gt;` tags for the
list item text. You can create multi-paragraph list items by indenting
the paragraphs by 4 spaces or 1 tab:
* A list item.
With multiple paragraphs.
* Another item in the list.
Output:
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;A list item.&lt;/p&gt;
&lt;p&gt;With multiple paragraphs.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Another item in the list.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
### Links ###
Markdown supports two styles for creating links: *inline* and
*reference*. With both styles, you use square brackets to delimit the
text you want to turn into a link.
Inline-style links use parentheses immediately after the link text.
For example:
This is an [example link](http://example.com/).
Output:
&lt;p&gt;This is an &lt;a href="http://example.com/"&gt;
example link&lt;/a&gt;.&lt;/p&gt;
Optionally, you may include a title attribute in the parentheses:
This is an [example link](http://example.com/ "With a Title").
Output:
&lt;p&gt;This is an &lt;a href="http://example.com/" title="With a Title"&gt;
example link&lt;/a&gt;.&lt;/p&gt;
Reference-style links allow you to refer to your links by names, which
you define elsewhere in your document:
I get 10 times more traffic from [Google][1] than from
[Yahoo][2] or [MSN][3].
[1]: http://google.com/ "Google"
[2]: http://search.yahoo.com/ "Yahoo Search"
[3]: http://search.msn.com/ "MSN Search"
Output:
&lt;p&gt;I get 10 times more traffic from &lt;a href="http://google.com/"
title="Google"&gt;Google&lt;/a&gt; than from &lt;a href="http://search.yahoo.com/"
title="Yahoo Search"&gt;Yahoo&lt;/a&gt; or &lt;a href="http://search.msn.com/"
title="MSN Search"&gt;MSN&lt;/a&gt;.&lt;/p&gt;
The title attribute is optional. Link names may contain letters,
numbers and spaces, but are *not* case sensitive:
I start my morning with a cup of coffee and
[The New York Times][NY Times].
[ny times]: http://www.nytimes.com/
Output:
&lt;p&gt;I start my morning with a cup of coffee and
&lt;a href="http://www.nytimes.com/"&gt;The New York Times&lt;/a&gt;.&lt;/p&gt;
### Images ###
Image syntax is very much like link syntax.
Inline (titles are optional):
![alt text](/path/to/img.jpg "Title")
Reference-style:
![alt text][id]
[id]: /path/to/img.jpg "Title"
Both of the above examples produce the same output:
&lt;img src="/path/to/img.jpg" alt="alt text" title="Title" /&gt;
### Code ###
In a regular paragraph, you can create code span by wrapping text in
backtick quotes. Any ampersands (`&amp;`) and angle brackets (`&lt;` or
`&gt;`) will automatically be translated into HTML entities. This makes
it easy to use Markdown to write about HTML example code:
I strongly recommend against using any `&lt;blink&gt;` tags.
I wish SmartyPants used named entities like `&amp;mdash;`
instead of decimal-encoded entites like `&amp;#8212;`.
Output:
&lt;p&gt;I strongly recommend against using any
&lt;code&gt;&amp;lt;blink&amp;gt;&lt;/code&gt; tags.&lt;/p&gt;
&lt;p&gt;I wish SmartyPants used named entities like
&lt;code&gt;&amp;amp;mdash;&lt;/code&gt; instead of decimal-encoded
entites like &lt;code&gt;&amp;amp;#8212;&lt;/code&gt;.&lt;/p&gt;
To specify an entire block of pre-formatted code, indent every line of
the block by 4 spaces or 1 tab. Just like with code spans, `&amp;`, `&lt;`,
and `&gt;` characters will be escaped automatically.
Markdown:
If you want your page to validate under XHTML 1.0 Strict,
you've got to put paragraph tags in your blockquotes:
&lt;blockquote&gt;
&lt;p&gt;For example.&lt;/p&gt;
&lt;/blockquote&gt;
Output:
&lt;p&gt;If you want your page to validate under XHTML 1.0 Strict,
you've got to put paragraph tags in your blockquotes:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;blockquote&amp;gt;
&amp;lt;p&amp;gt;For example.&amp;lt;/p&amp;gt;
&amp;lt;/blockquote&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
mode: 'markdown',
lineNumbers: true,
matchBrackets: true,
theme: "default"
});
</script>
<p>Optionally depends on the XML mode for properly highlighted inline XML blocks.</p>
<p><strong>MIME types defined:</strong> <code>text/x-markdown</code>.</p>
<p><strong>Parsing/Highlighting Tests:</strong> <a href="../../test/index.html#markdown_*">normal</a>, <a href="../../test/index.html#verbose,markdown_*">verbose</a>.</p>
</body>
</html>
CodeMirror.defineMode("markdown", function(cmCfg, modeCfg) {
var htmlFound = CodeMirror.mimeModes.hasOwnProperty("text/html");
var htmlMode = CodeMirror.getMode(cmCfg, htmlFound ? "text/html" : "text/plain");
var aliases = {
html: "htmlmixed",
js: "javascript",
json: "application/json",
c: "text/x-csrc",
"c++": "text/x-c++src",
java: "text/x-java",
csharp: "text/x-csharp",
"c#": "text/x-csharp"
};
var getMode = (function () {
var i, modes = {}, mimes = {}, mime;
var list = CodeMirror.listModes();
for (i = 0; i < list.length; i++) {
modes[list[i]] = list[i];
}
var mimesList = CodeMirror.listMIMEs();
for (i = 0; i < mimesList.length; i++) {
mime = mimesList[i].mime;
mimes[mime] = mimesList[i].mime;
}
for (var a in aliases) {
if (aliases[a] in modes || aliases[a] in mimes)
modes[a] = aliases[a];
}
return function (lang) {
return modes[lang] ? CodeMirror.getMode(cmCfg, modes[lang]) : null;
};
}());
// Should underscores in words open/close em/strong?
if (modeCfg.underscoresBreakWords === undefined)
modeCfg.underscoresBreakWords = true;
// Turn on fenced code blocks? ("```" to start/end)
if (modeCfg.fencedCodeBlocks === undefined) modeCfg.fencedCodeBlocks = false;
var codeDepth = 0;
var prevLineHasContent = false
, thisLineHasContent = false;
var header = 'header'
, code = 'comment'
, quote = 'quote'
, list = 'string'
, hr = 'hr'
, image = 'tag'
, linkinline = 'link'
, linkemail = 'link'
, linktext = 'link'
, linkhref = 'string'
, em = 'em'
, strong = 'strong'
, emstrong = 'emstrong';
var hrRE = /^([*\-=_])(?:\s*\1){2,}\s*$/
, ulRE = /^[*\-+]\s+/
, olRE = /^[0-9]+\.\s+/
, headerRE = /^(?:\={1,}|-{1,})$/
, textRE = /^[^!\[\]*_\\<>` "'(]+/;
function switchInline(stream, state, f) {
state.f = state.inline = f;
return f(stream, state);
}
function switchBlock(stream, state, f) {
state.f = state.block = f;
return f(stream, state);
}
// Blocks
function blankLine(state) {
// Reset linkTitle state
state.linkTitle = false;
// Reset EM state
state.em = false;
// Reset STRONG state
state.strong = false;
// Reset state.quote
state.quote = false;
if (!htmlFound && state.f == htmlBlock) {
state.f = inlineNormal;
state.block = blockNormal;
}
return null;
}
function blockNormal(stream, state) {
if (state.list !== false && state.indentationDiff >= 0) { // Continued list
if (state.indentationDiff < 4) { // Only adjust indentation if *not* a code block
state.indentation -= state.indentationDiff;
}
state.list = null;
} else { // No longer a list
state.list = false;
}
if (state.indentationDiff >= 4) {
state.indentation -= 4;
stream.skipToEnd();
return code;
} else if (stream.eatSpace()) {
return null;
} else if (stream.peek() === '#' || (prevLineHasContent && stream.match(headerRE)) ) {
state.header = true;
} else if (stream.eat('>')) {
state.indentation++;
state.quote = true;
} else if (stream.peek() === '[') {
return switchInline(stream, state, footnoteLink);
} else if (stream.match(hrRE, true)) {
return hr;
} else if (stream.match(ulRE, true) || stream.match(olRE, true)) {
state.indentation += 4;
state.list = true;
} else if (modeCfg.fencedCodeBlocks && stream.match(/^```([\w+#]*)/, true)) {
// try switching mode
state.localMode = getMode(RegExp.$1);
if (state.localMode) state.localState = state.localMode.startState();
switchBlock(stream, state, local);
return code;
}
return switchInline(stream, state, state.inline);
}
function htmlBlock(stream, state) {
var style = htmlMode.token(stream, state.htmlState);
if (htmlFound && style === 'tag' && state.htmlState.type !== 'openTag' && !state.htmlState.context) {
state.f = inlineNormal;
state.block = blockNormal;
}
if (state.md_inside && stream.current().indexOf(">")!=-1) {
state.f = inlineNormal;
state.block = blockNormal;
state.htmlState.context = undefined;
}
return style;
}
function local(stream, state) {
if (stream.sol() && stream.match(/^```/, true)) {
state.localMode = state.localState = null;
state.f = inlineNormal;
state.block = blockNormal;
return code;
} else if (state.localMode) {
return state.localMode.token(stream, state.localState);
} else {
stream.skipToEnd();
return code;
}
}
function codeBlock(stream, state) {
if(stream.match(codeBlockRE, true)){
state.f = inlineNormal;
state.block = blockNormal;
switchInline(stream, state, state.inline);
return code;
}
stream.skipToEnd();
return code;
}
// Inline
function getType(state) {
var styles = [];
if (state.strong) { styles.push(state.em ? emstrong : strong); }
else if (state.em) { styles.push(em); }
if (state.linkText) { styles.push(linktext); }
if (state.code) { styles.push(code); }
if (state.header) { styles.push(header); }
if (state.quote) { styles.push(quote); }
if (state.list !== false) { styles.push(list); }
return styles.length ? styles.join(' ') : null;
}
function handleText(stream, state) {
if (stream.match(textRE, true)) {
return getType(state);
}
return undefined;
}
function inlineNormal(stream, state) {
var style = state.text(stream, state);
if (typeof style !== 'undefined')
return style;
if (state.list) { // List marker (*, +, -, 1., etc)
state.list = null;
return list;
}
var ch = stream.next();
if (ch === '\\') {
stream.next();
return getType(state);
}
// Matches link titles present on next line
if (state.linkTitle) {
state.linkTitle = false;
var matchCh = ch;
if (ch === '(') {
matchCh = ')';
}
matchCh = (matchCh+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
var regex = '^\\s*(?:[^' + matchCh + '\\\\]+|\\\\\\\\|\\\\.)' + matchCh;
if (stream.match(new RegExp(regex), true)) {
return linkhref;
}
}
// If this block is changed, it may need to be updated in GFM mode
if (ch === '`') {
var t = getType(state);
var before = stream.pos;
stream.eatWhile('`');
var difference = 1 + stream.pos - before;
if (!state.code) {
codeDepth = difference;
state.code = true;
return getType(state);
} else {
if (difference === codeDepth) { // Must be exact
state.code = false;
return t;
}
return getType(state);
}
} else if (state.code) {
return getType(state);
}
if (ch === '!' && stream.match(/\[.*\] ?(?:\(|\[)/, false)) {
stream.match(/\[.*\]/);
state.inline = state.f = linkHref;
return image;
}
if (ch === '[' && stream.match(/.*\](\(| ?\[)/, false)) {
state.linkText = true;
return getType(state);
}
if (ch === ']' && state.linkText) {
var type = getType(state);
state.linkText = false;
state.inline = state.f = linkHref;
return type;
}
if (ch === '<' && stream.match(/^(https?|ftps?):\/\/(?:[^\\>]|\\.)+>/, true)) {
return switchInline(stream, state, inlineElement(linkinline, '>'));
}
if (ch === '<' && stream.match(/^[^> \\]+@(?:[^\\>]|\\.)+>/, true)) {
return switchInline(stream, state, inlineElement(linkemail, '>'));
}
if (ch === '<' && stream.match(/^\w/, false)) {
var md_inside = false;
if (stream.string.indexOf(">")!=-1) {
var atts = stream.string.substring(1,stream.string.indexOf(">"));
if (/markdown\s*=\s*('|"){0,1}1('|"){0,1}/.test(atts)) {
state.md_inside = true;
}
}
stream.backUp(1);
return switchBlock(stream, state, htmlBlock);
}
if (ch === '<' && stream.match(/^\/\w*?>/)) {
state.md_inside = false;
return "tag";
}
var ignoreUnderscore = false;
if (!modeCfg.underscoresBreakWords) {
if (ch === '_' && stream.peek() !== '_' && stream.match(/(\w)/, false)) {
var prevPos = stream.pos - 2;
if (prevPos >= 0) {
var prevCh = stream.string.charAt(prevPos);
if (prevCh !== '_' && prevCh.match(/(\w)/, false)) {
ignoreUnderscore = true;
}
}
}
}
var t = getType(state);
if (ch === '*' || (ch === '_' && !ignoreUnderscore)) {
if (state.strong === ch && stream.eat(ch)) { // Remove STRONG
state.strong = false;
return t;
} else if (!state.strong && stream.eat(ch)) { // Add STRONG
state.strong = ch;
return getType(state);
} else if (state.em === ch) { // Remove EM
state.em = false;
return t;
} else if (!state.em) { // Add EM
state.em = ch;
return getType(state);
}
} else if (ch === ' ') {
if (stream.eat('*') || stream.eat('_')) { // Probably surrounded by spaces
if (stream.peek() === ' ') { // Surrounded by spaces, ignore
return getType(state);
} else { // Not surrounded by spaces, back up pointer
stream.backUp(1);
}
}
}
return getType(state);
}
function linkHref(stream, state) {
// Check if space, and return NULL if so (to avoid marking the space)
if(stream.eatSpace()){
return null;
}
var ch = stream.next();
if (ch === '(' || ch === '[') {
return switchInline(stream, state, inlineElement(linkhref, ch === '(' ? ')' : ']'));
}
return 'error';
}
function footnoteLink(stream, state) {
if (stream.match(/^[^\]]*\]:/, true)) {
state.f = footnoteUrl;
return linktext;
}
return switchInline(stream, state, inlineNormal);
}
function footnoteUrl(stream, state) {
// Check if space, and return NULL if so (to avoid marking the space)
if(stream.eatSpace()){
return null;
}
// Match URL
stream.match(/^[^\s]+/, true);
// Check for link title
if (stream.peek() === undefined) { // End of line, set flag to check next line
state.linkTitle = true;
} else { // More content on line, check if link title
stream.match(/^(?:\s+(?:"(?:[^"\\]|\\\\|\\.)+"|'(?:[^'\\]|\\\\|\\.)+'|\((?:[^)\\]|\\\\|\\.)+\)))?/, true);
}
state.f = state.inline = inlineNormal;
return linkhref;
}
var savedInlineRE = [];
function inlineRE(endChar) {
if (!savedInlineRE[endChar]) {
// Escape endChar for RegExp (taken from http://stackoverflow.com/a/494122/526741)
endChar = (endChar+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
// Match any non-endChar, escaped character, as well as the closing
// endChar.
savedInlineRE[endChar] = new RegExp('^(?:[^\\\\]|\\\\.)*?(' + endChar + ')');
}
return savedInlineRE[endChar];
}
function inlineElement(type, endChar, next) {
next = next || inlineNormal;
return function(stream, state) {
stream.match(inlineRE(endChar));
state.inline = state.f = next;
return type;
};
}
return {
startState: function() {
prevLineHasContent = false;
thisLineHasContent = false;
return {
f: blockNormal,
block: blockNormal,
htmlState: CodeMirror.startState(htmlMode),
indentation: 0,
inline: inlineNormal,
text: handleText,
linkText: false,
linkTitle: false,
em: false,
strong: false,
header: false,
list: false,
quote: false
};
},
copyState: function(s) {
return {
f: s.f,
block: s.block,
htmlState: CodeMirror.copyState(htmlMode, s.htmlState),
indentation: s.indentation,
localMode: s.localMode,
localState: s.localMode ? CodeMirror.copyState(s.localMode, s.localState) : null,
inline: s.inline,
text: s.text,
linkTitle: s.linkTitle,
em: s.em,
strong: s.strong,
header: s.header,
list: s.list,
quote: s.quote,
md_inside: s.md_inside
};
},
token: function(stream, state) {
if (stream.sol()) {
if (stream.match(/^\s*$/, true)) {
prevLineHasContent = false;
return blankLine(state);
} else {
if(thisLineHasContent){
prevLineHasContent = true;
thisLineHasContent = false;
}
thisLineHasContent = true;
}
// Reset state.header
state.header = false;
// Reset state.code
state.code = false;
state.f = state.block;
var indentation = stream.match(/^\s*/, true)[0].replace(/\t/g, ' ').length;
var difference = Math.floor((indentation - state.indentation) / 4) * 4;
if (difference > 4) difference = 4;
indentation = state.indentation + difference;
state.indentationDiff = indentation - state.indentation;
state.indentation = indentation;
if (indentation > 0) { return null; }
}
return state.f(stream, state);
},
blankLine: blankLine,
getType: getType
};
}, "xml");
CodeMirror.defineMIME("text/x-markdown", "markdown");
// Initiate ModeTest and set defaults
var MT = ModeTest;
MT.modeName = 'markdown';
MT.modeOptions = {};
MT.testMode(
'plainText',
'foo',
[
null, 'foo'
]
);
// Code blocks using 4 spaces (regardless of CodeMirror.tabSize value)
MT.testMode(
'codeBlocksUsing4Spaces',
' foo',
[
null, ' ',
'comment', 'foo'
]
);
// Code blocks using 4 spaces with internal indentation
MT.testMode(
'codeBlocksUsing4SpacesIndentation',
' bar\n hello\n world\n foo\nbar',
[
null, ' ',
'comment', 'bar',
null, ' ',
'comment', 'hello',
null, ' ',
'comment', 'world',
null, ' ',
'comment', 'foo',
null, 'bar'
]
);
// Code blocks using 4 spaces with internal indentation
MT.testMode(
'codeBlocksUsing4SpacesIndentation',
' foo\n bar\n hello\n world',
[
null, ' foo',
null, ' ',
'comment', 'bar',
null, ' ',
'comment', 'hello',
null, ' ',
'comment', 'world'
]
);
// Code blocks using 1 tab (regardless of CodeMirror.indentWithTabs value)
MT.testMode(
'codeBlocksUsing1Tab',
'\tfoo',
[
null, '\t',
'comment', 'foo'
]
);
// Inline code using backticks
MT.testMode(
'inlineCodeUsingBackticks',
'foo `bar`',
[
null, 'foo ',
'comment', '`bar`'
]
);
// Block code using single backtick (shouldn't work)
MT.testMode(
'blockCodeSingleBacktick',
'`\nfoo\n`',
[
'comment', '`',
null, 'foo',
'comment', '`'
]
);
// Unclosed backticks
// Instead of simply marking as CODE, it would be nice to have an
// incomplete flag for CODE, that is styled slightly different.
MT.testMode(
'unclosedBackticks',
'foo `bar',
[
null, 'foo ',
'comment', '`bar'
]
);
// Per documentation: "To include a literal backtick character within a
// code span, you can use multiple backticks as the opening and closing
// delimiters"
MT.testMode(
'doubleBackticks',
'``foo ` bar``',
[
'comment', '``foo ` bar``'
]
);
// Tests based on Dingus
// http://daringfireball.net/projects/markdown/dingus
//
// Multiple backticks within an inline code block
MT.testMode(
'consecutiveBackticks',
'`foo```bar`',
[
'comment', '`foo```bar`'
]
);
// Multiple backticks within an inline code block with a second code block
MT.testMode(
'consecutiveBackticks',
'`foo```bar` hello `world`',
[
'comment', '`foo```bar`',
null, ' hello ',
'comment', '`world`'
]
);
// Unclosed with several different groups of backticks
MT.testMode(
'unclosedBackticks',
'``foo ``` bar` hello',
[
'comment', '``foo ``` bar` hello'
]
);
// Closed with several different groups of backticks
MT.testMode(
'closedBackticks',
'``foo ``` bar` hello`` world',
[
'comment', '``foo ``` bar` hello``',
null, ' world'
]
);
// atx headers
// http://daringfireball.net/projects/markdown/syntax#header
//
// H1
MT.testMode(
'atxH1',
'# foo',
[
'header', '# foo'
]
);
// H2
MT.testMode(
'atxH2',
'## foo',
[
'header', '## foo'
]
);
// H3
MT.testMode(
'atxH3',
'### foo',
[
'header', '### foo'
]
);
// H4
MT.testMode(
'atxH4',
'#### foo',
[
'header', '#### foo'
]
);
// H5
MT.testMode(
'atxH5',
'##### foo',
[
'header', '##### foo'
]
);
// H6
MT.testMode(
'atxH6',
'###### foo',
[
'header', '###### foo'
]
);
// H6 - 7x '#' should still be H6, per Dingus
// http://daringfireball.net/projects/markdown/dingus
MT.testMode(
'atxH6NotH7',
'####### foo',
[
'header', '####### foo'
]
);
// Setext headers - H1, H2
// Per documentation, "Any number of underlining =’s or -’s will work."
// http://daringfireball.net/projects/markdown/syntax#header
// Ideally, the text would be marked as `header` as well, but this is
// not really feasible at the moment. So, instead, we're testing against
// what works today, to avoid any regressions.
//
// Check if single underlining = works
MT.testMode(
'setextH1',
'foo\n=',
[
null, 'foo',
'header', '='
]
);
// Check if 3+ ='s work
MT.testMode(
'setextH1',
'foo\n===',
[
null, 'foo',
'header', '==='
]
);
// Check if single underlining - works
MT.testMode(
'setextH2',
'foo\n-',
[
null, 'foo',
'header', '-'
]
);
// Check if 3+ -'s work
MT.testMode(
'setextH2',
'foo\n---',
[
null, 'foo',
'header', '---'
]
);
// Single-line blockquote with trailing space
MT.testMode(
'blockquoteSpace',
'> foo',
[
'quote', '> foo'
]
);
// Single-line blockquote
MT.testMode(
'blockquoteNoSpace',
'>foo',
[
'quote', '>foo'
]
);
// Single-line blockquote followed by normal paragraph
MT.testMode(
'blockquoteThenParagraph',
'>foo\n\nbar',
[
'quote', '>foo',
null, 'bar'
]
);
// Multi-line blockquote (lazy mode)
MT.testMode(
'multiBlockquoteLazy',
'>foo\nbar',
[
'quote', '>foo',
'quote', 'bar'
]
);
// Multi-line blockquote followed by normal paragraph (lazy mode)
MT.testMode(
'multiBlockquoteLazyThenParagraph',
'>foo\nbar\n\nhello',
[
'quote', '>foo',
'quote', 'bar',
null, 'hello'
]
);
// Multi-line blockquote (non-lazy mode)
MT.testMode(
'multiBlockquote',
'>foo\n>bar',
[
'quote', '>foo',
'quote', '>bar'
]
);
// Multi-line blockquote followed by normal paragraph (non-lazy mode)
MT.testMode(
'multiBlockquoteThenParagraph',
'>foo\n>bar\n\nhello',
[
'quote', '>foo',
'quote', '>bar',
null, 'hello'
]
);
// Check list types
MT.testMode(
'listAsterisk',
'* foo\n* bar',
[
'string', '* foo',
'string', '* bar'
]
);
MT.testMode(
'listPlus',
'+ foo\n+ bar',
[
'string', '+ foo',
'string', '+ bar'
]
);
MT.testMode(
'listDash',
'- foo\n- bar',
[
'string', '- foo',
'string', '- bar'
]
);
MT.testMode(
'listNumber',
'1. foo\n2. bar',
[
'string', '1. foo',
'string', '2. bar'
]
);
// Formatting in lists (*)
MT.testMode(
'listAsteriskFormatting',
'* *foo* bar\n\n* **foo** bar\n\n* ***foo*** bar\n\n* `foo` bar',
[
'string', '* ',
'string em', '*foo*',
'string', ' bar',
'string', '* ',
'string strong', '**foo**',
'string', ' bar',
'string', '* ',
'string strong', '**',
'string emstrong', '*foo**',
'string em', '*',
'string', ' bar',
'string', '* ',
'string comment', '`foo`',
'string', ' bar'
]
);
// Formatting in lists (+)
MT.testMode(
'listPlusFormatting',
'+ *foo* bar\n\n+ **foo** bar\n\n+ ***foo*** bar\n\n+ `foo` bar',
[
'string', '+ ',
'string em', '*foo*',
'string', ' bar',
'string', '+ ',
'string strong', '**foo**',
'string', ' bar',
'string', '+ ',
'string strong', '**',
'string emstrong', '*foo**',
'string em', '*',
'string', ' bar',
'string', '+ ',
'string comment', '`foo`',
'string', ' bar'
]
);
// Formatting in lists (-)
MT.testMode(
'listDashFormatting',
'- *foo* bar\n\n- **foo** bar\n\n- ***foo*** bar\n\n- `foo` bar',
[
'string', '- ',
'string em', '*foo*',
'string', ' bar',
'string', '- ',
'string strong', '**foo**',
'string', ' bar',
'string', '- ',
'string strong', '**',
'string emstrong', '*foo**',
'string em', '*',
'string', ' bar',
'string', '- ',
'string comment', '`foo`',
'string', ' bar'
]
);
// Formatting in lists (1.)
MT.testMode(
'listNumberFormatting',
'1. *foo* bar\n\n2. **foo** bar\n\n3. ***foo*** bar\n\n4. `foo` bar',
[
'string', '1. ',
'string em', '*foo*',
'string', ' bar',
'string', '2. ',
'string strong', '**foo**',
'string', ' bar',
'string', '3. ',
'string strong', '**',
'string emstrong', '*foo**',
'string em', '*',
'string', ' bar',
'string', '4. ',
'string comment', '`foo`',
'string', ' bar'
]
);
// Paragraph lists
MT.testMode(
'listParagraph',
'* foo\n\n* bar',
[
'string', '* foo',
'string', '* bar'
]
);
// Multi-paragraph lists
//
// 4 spaces
MT.testMode(
'listMultiParagraph',
'* foo\n\n* bar\n\n hello',
[
'string', '* foo',
'string', '* bar',
null, ' ',
'string', 'hello'
]
);
// 4 spaces, extra blank lines (should still be list, per Dingus)
MT.testMode(
'listMultiParagraphExtra',
'* foo\n\n* bar\n\n\n hello',
[
'string', '* foo',
'string', '* bar',
null, ' ',
'string', 'hello'
]
);
// 4 spaces, plus 1 space (should still be list, per Dingus)
MT.testMode(
'listMultiParagraphExtraSpace',
'* foo\n\n* bar\n\n hello\n\n world',
[
'string', '* foo',
'string', '* bar',
null, ' ',
'string', 'hello',
null, ' ',
'string', 'world'
]
);
// 1 tab
MT.testMode(
'listTab',
'* foo\n\n* bar\n\n\thello',
[
'string', '* foo',
'string', '* bar',
null, '\t',
'string', 'hello'
]
);
// No indent
MT.testMode(
'listNoIndent',
'* foo\n\n* bar\n\nhello',
[
'string', '* foo',
'string', '* bar',
null, 'hello'
]
);
// Blockquote
MT.testMode(
'blockquote',
'* foo\n\n* bar\n\n > hello',
[
'string', '* foo',
'string', '* bar',
null, ' ',
'string quote', '> hello'
]
);
// Code block
MT.testMode(
'blockquoteCode',
'* foo\n\n* bar\n\n > hello\n\n world',
[
'string', '* foo',
'string', '* bar',
null, ' ',
'comment', '> hello',
null, ' ',
'string', 'world'
]
);
// Code block followed by text
MT.testMode(
'blockquoteCodeText',
'* foo\n\n bar\n\n hello\n\n world',
[
'string', '* foo',
null, ' ',
'string', 'bar',
null, ' ',
'comment', 'hello',
null, ' ',
'string', 'world'
]
);
// Nested list
//
// *
MT.testMode(
'listAsteriskNested',
'* foo\n\n * bar',
[
'string', '* foo',
null, ' ',
'string', '* bar'
]
);
// +
MT.testMode(
'listPlusNested',
'+ foo\n\n + bar',
[
'string', '+ foo',
null, ' ',
'string', '+ bar'
]
);
// -
MT.testMode(
'listDashNested',
'- foo\n\n - bar',
[
'string', '- foo',
null, ' ',
'string', '- bar'
]
);
// 1.
MT.testMode(
'listNumberNested',
'1. foo\n\n 2. bar',
[
'string', '1. foo',
null, ' ',
'string', '2. bar'
]
);
// Mixed
MT.testMode(
'listMixed',
'* foo\n\n + bar\n\n - hello\n\n 1. world',
[
'string', '* foo',
null, ' ',
'string', '+ bar',
null, ' ',
'string', '- hello',
null, ' ',
'string', '1. world'
]
);
// Blockquote
MT.testMode(
'listBlockquote',
'* foo\n\n + bar\n\n > hello',
[
'string', '* foo',
null, ' ',
'string', '+ bar',
null, ' ',
'quote string', '> hello'
]
);
// Code
MT.testMode(
'listCode',
'* foo\n\n + bar\n\n hello',
[
'string', '* foo',
null, ' ',
'string', '+ bar',
null, ' ',
'comment', 'hello'
]
);
// Code with internal indentation
MT.testMode(
'listCodeIndentation',
'* foo\n\n bar\n hello\n world\n foo\n bar',
[
'string', '* foo',
null, ' ',
'comment', 'bar',
null, ' ',
'comment', 'hello',
null, ' ',
'comment', 'world',
null, ' ',
'comment', 'foo',
null, ' ',
'string', 'bar'
]
);
// Code followed by text
MT.testMode(
'listCodeText',
'* foo\n\n bar\n\nhello',
[
'string', '* foo',
null, ' ',
'comment', 'bar',
null, 'hello'
]
);
// Following tests directly from official Markdown documentation
// http://daringfireball.net/projects/markdown/syntax#hr
MT.testMode(
'hrSpace',
'* * *',
[
'hr', '* * *'
]
);
MT.testMode(
'hr',
'***',
[
'hr', '***'
]
);
MT.testMode(
'hrLong',
'*****',
[
'hr', '*****'
]
);
MT.testMode(
'hrSpaceDash',
'- - -',
[
'hr', '- - -'
]
);
MT.testMode(
'hrDashLong',
'---------------------------------------',
[
'hr', '---------------------------------------'
]
);
// Inline link with title
MT.testMode(
'linkTitle',
'[foo](http://example.com/ "bar") hello',
[
'link', '[foo]',
'string', '(http://example.com/ "bar")',
null, ' hello'
]
);
// Inline link without title
MT.testMode(
'linkNoTitle',
'[foo](http://example.com/) bar',
[
'link', '[foo]',
'string', '(http://example.com/)',
null, ' bar'
]
);
// Inline link with Em
MT.testMode(
'linkEm',
'[*foo*](http://example.com/) bar',
[
'link', '[',
'link em', '*foo*',
'link', ']',
'string', '(http://example.com/)',
null, ' bar'
]
);
// Inline link with Strong
MT.testMode(
'linkStrong',
'[**foo**](http://example.com/) bar',
[
'link', '[',
'link strong', '**foo**',
'link', ']',
'string', '(http://example.com/)',
null, ' bar'
]
);
// Inline link with EmStrong
MT.testMode(
'linkEmStrong',
'[***foo***](http://example.com/) bar',
[
'link', '[',
'link strong', '**',
'link emstrong', '*foo**',
'link em', '*',
'link', ']',
'string', '(http://example.com/)',
null, ' bar'
]
);
// Image with title
MT.testMode(
'imageTitle',
'![foo](http://example.com/ "bar") hello',
[
'tag', '![foo]',
'string', '(http://example.com/ "bar")',
null, ' hello'
]
);
// Image without title
MT.testMode(
'imageNoTitle',
'![foo](http://example.com/) bar',
[
'tag', '![foo]',
'string', '(http://example.com/)',
null, ' bar'
]
);
// Image with asterisks
MT.testMode(
'imageAsterisks',
'![*foo*](http://example.com/) bar',
[
'tag', '![*foo*]',
'string', '(http://example.com/)',
null, ' bar'
]
);
// Not a link. Should be normal text due to square brackets being used
// regularly in text, especially in quoted material, and no space is allowed
// between square brackets and parentheses (per Dingus).
MT.testMode(
'notALink',
'[foo] (bar)',
[
null, '[foo] (bar)'
]
);
// Reference-style links
MT.testMode(
'linkReference',
'[foo][bar] hello',
[
'link', '[foo]',
'string', '[bar]',
null, ' hello'
]
);
// Reference-style links with Em
MT.testMode(
'linkReferenceEm',
'[*foo*][bar] hello',
[
'link', '[',
'link em', '*foo*',
'link', ']',
'string', '[bar]',
null, ' hello'
]
);
// Reference-style links with Strong
MT.testMode(
'linkReferenceStrong',
'[**foo**][bar] hello',
[
'link', '[',
'link strong', '**foo**',
'link', ']',
'string', '[bar]',
null, ' hello'
]
);
// Reference-style links with EmStrong
MT.testMode(
'linkReferenceEmStrong',
'[***foo***][bar] hello',
[
'link', '[',
'link strong', '**',
'link emstrong', '*foo**',
'link em', '*',
'link', ']',
'string', '[bar]',
null, ' hello'
]
);
// Reference-style links with optional space separator (per docuentation)
// "You can optionally use a space to separate the sets of brackets"
MT.testMode(
'linkReferenceSpace',
'[foo] [bar] hello',
[
'link', '[foo]',
null, ' ',
'string', '[bar]',
null, ' hello'
]
);
// Should only allow a single space ("...use *a* space...")
MT.testMode(
'linkReferenceDoubleSpace',
'[foo] [bar] hello',
[
null, '[foo] [bar] hello'
]
);
// Reference-style links with implicit link name
MT.testMode(
'linkImplicit',
'[foo][] hello',
[
'link', '[foo]',
'string', '[]',
null, ' hello'
]
);
// @todo It would be nice if, at some point, the document was actually
// checked to see if the referenced link exists
// Link label, for reference-style links (taken from documentation)
//
// No title
MT.testMode(
'labelNoTitle',
'[foo]: http://example.com/',
[
'link', '[foo]:',
null, ' ',
'string', 'http://example.com/'
]
);
// Space in ID and title
MT.testMode(
'labelSpaceTitle',
'[foo bar]: http://example.com/ "hello"',
[
'link', '[foo bar]:',
null, ' ',
'string', 'http://example.com/ "hello"'
]
);
// Double title
MT.testMode(
'labelDoubleTitle',
'[foo bar]: http://example.com/ "hello" "world"',
[
'link', '[foo bar]:',
null, ' ',
'string', 'http://example.com/ "hello"',
null, ' "world"'
]
);
// Double quotes around title
MT.testMode(
'labelTitleDoubleQuotes',
'[foo]: http://example.com/ "bar"',
[
'link', '[foo]:',
null, ' ',
'string', 'http://example.com/ "bar"'
]
);
// Single quotes around title
MT.testMode(
'labelTitleSingleQuotes',
'[foo]: http://example.com/ \'bar\'',
[
'link', '[foo]:',
null, ' ',
'string', 'http://example.com/ \'bar\''
]
);
// Parentheses around title
MT.testMode(
'labelTitleParenthese',
'[foo]: http://example.com/ (bar)',
[
'link', '[foo]:',
null, ' ',
'string', 'http://example.com/ (bar)'
]
);
// Invalid title
MT.testMode(
'labelTitleInvalid',
'[foo]: http://example.com/ bar',
[
'link', '[foo]:',
null, ' ',
'string', 'http://example.com/',
null, ' bar'
]
);
// Angle brackets around URL
MT.testMode(
'labelLinkAngleBrackets',
'[foo]: <http://example.com/> "bar"',
[
'link', '[foo]:',
null, ' ',
'string', '<http://example.com/> "bar"'
]
);
// Title on next line per documentation (double quotes)
MT.testMode(
'labelTitleNextDoubleQuotes',
'[foo]: http://example.com/\n"bar" hello',
[
'link', '[foo]:',
null, ' ',
'string', 'http://example.com/',
'string', '"bar"',
null, ' hello'
]
);
// Title on next line per documentation (single quotes)
MT.testMode(
'labelTitleNextSingleQuotes',
'[foo]: http://example.com/\n\'bar\' hello',
[
'link', '[foo]:',
null, ' ',
'string', 'http://example.com/',
'string', '\'bar\'',
null, ' hello'
]
);
// Title on next line per documentation (parentheses)
MT.testMode(
'labelTitleNextParenthese',
'[foo]: http://example.com/\n(bar) hello',
[
'link', '[foo]:',
null, ' ',
'string', 'http://example.com/',
'string', '(bar)',
null, ' hello'
]
);
// Title on next line per documentation (mixed)
MT.testMode(
'labelTitleNextMixed',
'[foo]: http://example.com/\n(bar" hello',
[
'link', '[foo]:',
null, ' ',
'string', 'http://example.com/',
null, '(bar" hello'
]
);
// Automatic links
MT.testMode(
'linkWeb',
'<http://example.com/> foo',
[
'link', '<http://example.com/>',
null, ' foo'
]
);
// Automatic email links
MT.testMode(
'linkEmail',
'<user@example.com> foo',
[
'link', '<user@example.com>',
null, ' foo'
]
);
// Single asterisk
MT.testMode(
'emAsterisk',
'*foo* bar',
[
'em', '*foo*',
null, ' bar'
]
);
// Single underscore
MT.testMode(
'emUnderscore',
'_foo_ bar',
[
'em', '_foo_',
null, ' bar'
]
);
// Emphasis characters within a word
MT.testMode(
'emInWordAsterisk',
'foo*bar*hello',
[
null, 'foo',
'em', '*bar*',
null, 'hello'
]
);
MT.testMode(
'emInWordUnderscore',
'foo_bar_hello',
[
null, 'foo',
'em', '_bar_',
null, 'hello'
]
);
// Per documentation: "...surround an * or _ with spaces, it’ll be
// treated as a literal asterisk or underscore."
//
// Inside EM
MT.testMode(
'emEscapedBySpaceIn',
'foo _bar _ hello_ world',
[
null, 'foo ',
'em', '_bar _ hello_',
null, ' world'
]
);
// Outside EM
MT.testMode(
'emEscapedBySpaceOut',
'foo _ bar_hello_world',
[
null, 'foo _ bar',
'em', '_hello_',
null, 'world'
]
);
// Unclosed emphasis characters
// Instead of simply marking as EM / STRONG, it would be nice to have an
// incomplete flag for EM and STRONG, that is styled slightly different.
MT.testMode(
'emIncompleteAsterisk',
'foo *bar',
[
null, 'foo ',
'em', '*bar'
]
);
MT.testMode(
'emIncompleteUnderscore',
'foo _bar',
[
null, 'foo ',
'em', '_bar'
]
);
// Double asterisk
MT.testMode(
'strongAsterisk',
'**foo** bar',
[
'strong', '**foo**',
null, ' bar'
]
);
// Double underscore
MT.testMode(
'strongUnderscore',
'__foo__ bar',
[
'strong', '__foo__',
null, ' bar'
]
);
// Triple asterisk
MT.testMode(
'emStrongAsterisk',
'*foo**bar*hello** world',
[
'em', '*foo',
'emstrong', '**bar*',
'strong', 'hello**',
null, ' world'
]
);
// Triple underscore
MT.testMode(
'emStrongUnderscore',
'_foo__bar_hello__ world',
[
'em', '_foo',
'emstrong', '__bar_',
'strong', 'hello__',
null, ' world'
]
);
// Triple mixed
// "...same character must be used to open and close an emphasis span.""
MT.testMode(
'emStrongMixed',
'_foo**bar*hello__ world',
[
'em', '_foo',
'emstrong', '**bar*hello__ world'
]
);
MT.testMode(
'emStrongMixed',
'*foo__bar_hello** world',
[
'em', '*foo',
'emstrong', '__bar_hello** world'
]
);
// These characters should be escaped:
// \ backslash
// ` backtick
// * asterisk
// _ underscore
// {} curly braces
// [] square brackets
// () parentheses
// # hash mark
// + plus sign
// - minus sign (hyphen)
// . dot
// ! exclamation mark
//
// Backtick (code)
MT.testMode(
'escapeBacktick',
'foo \\`bar\\`',
[
null, 'foo \\`bar\\`'
]
);
MT.testMode(
'doubleEscapeBacktick',
'foo \\\\`bar\\\\`',
[
null, 'foo \\\\',
'comment', '`bar\\\\`'
]
);
// Asterisk (em)
MT.testMode(
'escapeAsterisk',
'foo \\*bar\\*',
[
null, 'foo \\*bar\\*'
]
);
MT.testMode(
'doubleEscapeAsterisk',
'foo \\\\*bar\\\\*',
[
null, 'foo \\\\',
'em', '*bar\\\\*'
]
);
// Underscore (em)
MT.testMode(
'escapeUnderscore',
'foo \\_bar\\_',
[
null, 'foo \\_bar\\_'
]
);
MT.testMode(
'doubleEscapeUnderscore',
'foo \\\\_bar\\\\_',
[
null, 'foo \\\\',
'em', '_bar\\\\_'
]
);
// Hash mark (headers)
MT.testMode(
'escapeHash',
'\\# foo',
[
null, '\\# foo'
]
);
MT.testMode(
'doubleEscapeHash',
'\\\\# foo',
[
null, '\\\\# foo'
]
);
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: MySQL mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="mysql.js"></script>
<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
<link rel="stylesheet" href="../../doc/docs.css">
</head>
<body>
<h1>CodeMirror: MySQL mode</h1>
<form><textarea id="code" name="code">
-- Comment for the code
-- MySQL Mode for CodeMirror2 by MySQLTools http://github.com/partydroid/MySQL-Tools
SELECT UNIQUE `var1` as `variable`,
MAX(`var5`) as `max`,
MIN(`var5`) as `min`,
STDEV(`var5`) as `dev`
FROM `table`
LEFT JOIN `table2` ON `var2` = `variable`
ORDER BY `var3` DESC
GROUP BY `groupvar`
LIMIT 0,30;
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
mode: "text/x-mysql",
tabMode: "indent",
matchBrackets: true
});
</script>
<p><strong>MIME types defined:</strong> <code>text/x-mysql</code>.</p>
</body>
</html>
/*
* MySQL Mode for CodeMirror 2 by MySQL-Tools
* @author James Thorne (partydroid)
* @link http://github.com/partydroid/MySQL-Tools
* @link http://mysqltools.org
* @version 02/Jan/2012
*/
CodeMirror.defineMode("mysql", function(config) {
var indentUnit = config.indentUnit;
var curPunc;
function wordRegexp(words) {
return new RegExp("^(?:" + words.join("|") + ")$", "i");
}
var ops = wordRegexp(["str", "lang", "langmatches", "datatype", "bound", "sameterm", "isiri", "isuri",
"isblank", "isliteral", "union", "a"]);
var keywords = wordRegexp([
('ACCESSIBLE'),('ALTER'),('AS'),('BEFORE'),('BINARY'),('BY'),('CASE'),('CHARACTER'),('COLUMN'),('CONTINUE'),('CROSS'),('CURRENT_TIMESTAMP'),('DATABASE'),('DAY_MICROSECOND'),('DEC'),('DEFAULT'),
('DESC'),('DISTINCT'),('DOUBLE'),('EACH'),('ENCLOSED'),('EXIT'),('FETCH'),('FLOAT8'),('FOREIGN'),('GRANT'),('HIGH_PRIORITY'),('HOUR_SECOND'),('IN'),('INNER'),('INSERT'),('INT2'),('INT8'),
('INTO'),('JOIN'),('KILL'),('LEFT'),('LINEAR'),('LOCALTIME'),('LONG'),('LOOP'),('MATCH'),('MEDIUMTEXT'),('MINUTE_SECOND'),('NATURAL'),('NULL'),('OPTIMIZE'),('OR'),('OUTER'),('PRIMARY'),
('RANGE'),('READ_WRITE'),('REGEXP'),('REPEAT'),('RESTRICT'),('RIGHT'),('SCHEMAS'),('SENSITIVE'),('SHOW'),('SPECIFIC'),('SQLSTATE'),('SQL_CALC_FOUND_ROWS'),('STARTING'),('TERMINATED'),
('TINYINT'),('TRAILING'),('UNDO'),('UNLOCK'),('USAGE'),('UTC_DATE'),('VALUES'),('VARCHARACTER'),('WHERE'),('WRITE'),('ZEROFILL'),('ALL'),('AND'),('ASENSITIVE'),('BIGINT'),('BOTH'),('CASCADE'),
('CHAR'),('COLLATE'),('CONSTRAINT'),('CREATE'),('CURRENT_TIME'),('CURSOR'),('DAY_HOUR'),('DAY_SECOND'),('DECLARE'),('DELETE'),('DETERMINISTIC'),('DIV'),('DUAL'),('ELSEIF'),('EXISTS'),('FALSE'),
('FLOAT4'),('FORCE'),('FULLTEXT'),('HAVING'),('HOUR_MINUTE'),('IGNORE'),('INFILE'),('INSENSITIVE'),('INT1'),('INT4'),('INTERVAL'),('ITERATE'),('KEYS'),('LEAVE'),('LIMIT'),('LOAD'),('LOCK'),
('LONGTEXT'),('MASTER_SSL_VERIFY_SERVER_CERT'),('MEDIUMINT'),('MINUTE_MICROSECOND'),('MODIFIES'),('NO_WRITE_TO_BINLOG'),('ON'),('OPTIONALLY'),('OUT'),('PRECISION'),('PURGE'),('READS'),
('REFERENCES'),('RENAME'),('REQUIRE'),('REVOKE'),('SCHEMA'),('SELECT'),('SET'),('SPATIAL'),('SQLEXCEPTION'),('SQL_BIG_RESULT'),('SSL'),('TABLE'),('TINYBLOB'),('TO'),('TRUE'),('UNIQUE'),
('UPDATE'),('USING'),('UTC_TIMESTAMP'),('VARCHAR'),('WHEN'),('WITH'),('YEAR_MONTH'),('ADD'),('ANALYZE'),('ASC'),('BETWEEN'),('BLOB'),('CALL'),('CHANGE'),('CHECK'),('CONDITION'),('CONVERT'),
('CURRENT_DATE'),('CURRENT_USER'),('DATABASES'),('DAY_MINUTE'),('DECIMAL'),('DELAYED'),('DESCRIBE'),('DISTINCTROW'),('DROP'),('ELSE'),('ESCAPED'),('EXPLAIN'),('FLOAT'),('FOR'),('FROM'),
('GROUP'),('HOUR_MICROSECOND'),('IF'),('INDEX'),('INOUT'),('INT'),('INT3'),('INTEGER'),('IS'),('KEY'),('LEADING'),('LIKE'),('LINES'),('LOCALTIMESTAMP'),('LONGBLOB'),('LOW_PRIORITY'),
('MEDIUMBLOB'),('MIDDLEINT'),('MOD'),('NOT'),('NUMERIC'),('OPTION'),('ORDER'),('OUTFILE'),('PROCEDURE'),('READ'),('REAL'),('RELEASE'),('REPLACE'),('RETURN'),('RLIKE'),('SECOND_MICROSECOND'),
('SEPARATOR'),('SMALLINT'),('SQL'),('SQLWARNING'),('SQL_SMALL_RESULT'),('STRAIGHT_JOIN'),('THEN'),('TINYTEXT'),('TRIGGER'),('UNION'),('UNSIGNED'),('USE'),('UTC_TIME'),('VARBINARY'),('VARYING'),
('WHILE'),('XOR'),('FULL'),('COLUMNS'),('MIN'),('MAX'),('STDEV'),('COUNT')
]);
var operatorChars = /[*+\-<>=&|]/;
function tokenBase(stream, state) {
var ch = stream.next();
curPunc = null;
if (ch == "$" || ch == "?") {
stream.match(/^[\w\d]*/);
return "variable-2";
}
else if (ch == "<" && !stream.match(/^[\s\u00a0=]/, false)) {
stream.match(/^[^\s\u00a0>]*>?/);
return "atom";
}
else if (ch == "\"" || ch == "'") {
state.tokenize = tokenLiteral(ch);
return state.tokenize(stream, state);
}
else if (ch == "`") {
state.tokenize = tokenOpLiteral(ch);
return state.tokenize(stream, state);
}
else if (/[{}\(\),\.;\[\]]/.test(ch)) {
curPunc = ch;
return null;
}
else if (ch == "-") {
var ch2 = stream.next();
if (ch2=="-") {
stream.skipToEnd();
return "comment";
}
}
else if (operatorChars.test(ch)) {
stream.eatWhile(operatorChars);
return null;
}
else if (ch == ":") {
stream.eatWhile(/[\w\d\._\-]/);
return "atom";
}
else {
stream.eatWhile(/[_\w\d]/);
if (stream.eat(":")) {
stream.eatWhile(/[\w\d_\-]/);
return "atom";
}
var word = stream.current(), type;
if (ops.test(word))
return null;
else if (keywords.test(word))
return "keyword";
else
return "variable";
}
}
function tokenLiteral(quote) {
return function(stream, state) {
var escaped = false, ch;
while ((ch = stream.next()) != null) {
if (ch == quote && !escaped) {
state.tokenize = tokenBase;
break;
}
escaped = !escaped && ch == "\\";
}
return "string";
};
}
function tokenOpLiteral(quote) {
return function(stream, state) {
var escaped = false, ch;
while ((ch = stream.next()) != null) {
if (ch == quote && !escaped) {
state.tokenize = tokenBase;
break;
}
escaped = !escaped && ch == "\\";
}
return "variable-2";
};
}
function pushContext(state, type, col) {
state.context = {prev: state.context, indent: state.indent, col: col, type: type};
}
function popContext(state) {
state.indent = state.context.indent;
state.context = state.context.prev;
}
return {
startState: function(base) {
return {tokenize: tokenBase,
context: null,
indent: 0,
col: 0};
},
token: function(stream, state) {
if (stream.sol()) {
if (state.context && state.context.align == null) state.context.align = false;
state.indent = stream.indentation();
}
if (stream.eatSpace()) return null;
var style = state.tokenize(stream, state);
if (style != "comment" && state.context && state.context.align == null && state.context.type != "pattern") {
state.context.align = true;
}
if (curPunc == "(") pushContext(state, ")", stream.column());
else if (curPunc == "[") pushContext(state, "]", stream.column());
else if (curPunc == "{") pushContext(state, "}", stream.column());
else if (/[\]\}\)]/.test(curPunc)) {
while (state.context && state.context.type == "pattern") popContext(state);
if (state.context && curPunc == state.context.type) popContext(state);
}
else if (curPunc == "." && state.context && state.context.type == "pattern") popContext(state);
else if (/atom|string|variable/.test(style) && state.context) {
if (/[\}\]]/.test(state.context.type))
pushContext(state, "pattern", stream.column());
else if (state.context.type == "pattern" && !state.context.align) {
state.context.align = true;
state.context.col = stream.column();
}
}
return style;
},
indent: function(state, textAfter) {
var firstChar = textAfter && textAfter.charAt(0);
var context = state.context;
if (/[\]\}]/.test(firstChar))
while (context && context.type == "pattern") context = context.prev;
var closing = context && firstChar == context.type;
if (!context)
return 0;
else if (context.type == "pattern")
return context.col;
else if (context.align)
return context.col + (closing ? 0 : 1);
else
return context.indent + (closing ? 0 : indentUnit);
}
};
});
CodeMirror.defineMIME("text/x-mysql", "mysql");
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: NTriples mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="ntriples.js"></script>
<link rel="stylesheet" href="../../doc/docs.css">
<style type="text/css">
.CodeMirror {
border: 1px solid #eee;
}
</style>
</head>
<body>
<h1>CodeMirror: NTriples mode</h1>
<form>
<textarea id="ntriples" name="ntriples">
<http://Sub1> <http://pred1> <http://obj> .
<http://Sub2> <http://pred2#an2> "literal 1" .
<http://Sub3#an3> <http://pred3> _:bnode3 .
_:bnode4 <http://pred4> "literal 2"@lang .
_:bnode5 <http://pred5> "literal 3"^^<http://type> .
</textarea>
</form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("ntriples"), {});
</script>
<p><strong>MIME types defined:</strong> <code>text/n-triples</code>.</p>
</body>
</html>
/**********************************************************
* This script provides syntax highlighting support for
* the Ntriples format.
* Ntriples format specification:
* http://www.w3.org/TR/rdf-testcases/#ntriples
***********************************************************/
/*
The following expression defines the defined ASF grammar transitions.
pre_subject ->
{
( writing_subject_uri | writing_bnode_uri )
-> pre_predicate
-> writing_predicate_uri
-> pre_object
-> writing_object_uri | writing_object_bnode |
(
writing_object_literal
-> writing_literal_lang | writing_literal_type
)
-> post_object
-> BEGIN
} otherwise {
-> ERROR
}
*/
CodeMirror.defineMode("ntriples", function() {
var Location = {
PRE_SUBJECT : 0,
WRITING_SUB_URI : 1,
WRITING_BNODE_URI : 2,
PRE_PRED : 3,
WRITING_PRED_URI : 4,
PRE_OBJ : 5,
WRITING_OBJ_URI : 6,
WRITING_OBJ_BNODE : 7,
WRITING_OBJ_LITERAL : 8,
WRITING_LIT_LANG : 9,
WRITING_LIT_TYPE : 10,
POST_OBJ : 11,
ERROR : 12
};
function transitState(currState, c) {
var currLocation = currState.location;
var ret;
// Opening.
if (currLocation == Location.PRE_SUBJECT && c == '<') ret = Location.WRITING_SUB_URI;
else if(currLocation == Location.PRE_SUBJECT && c == '_') ret = Location.WRITING_BNODE_URI;
else if(currLocation == Location.PRE_PRED && c == '<') ret = Location.WRITING_PRED_URI;
else if(currLocation == Location.PRE_OBJ && c == '<') ret = Location.WRITING_OBJ_URI;
else if(currLocation == Location.PRE_OBJ && c == '_') ret = Location.WRITING_OBJ_BNODE;
else if(currLocation == Location.PRE_OBJ && c == '"') ret = Location.WRITING_OBJ_LITERAL;
// Closing.
else if(currLocation == Location.WRITING_SUB_URI && c == '>') ret = Location.PRE_PRED;
else if(currLocation == Location.WRITING_BNODE_URI && c == ' ') ret = Location.PRE_PRED;
else if(currLocation == Location.WRITING_PRED_URI && c == '>') ret = Location.PRE_OBJ;
else if(currLocation == Location.WRITING_OBJ_URI && c == '>') ret = Location.POST_OBJ;
else if(currLocation == Location.WRITING_OBJ_BNODE && c == ' ') ret = Location.POST_OBJ;
else if(currLocation == Location.WRITING_OBJ_LITERAL && c == '"') ret = Location.POST_OBJ;
else if(currLocation == Location.WRITING_LIT_LANG && c == ' ') ret = Location.POST_OBJ;
else if(currLocation == Location.WRITING_LIT_TYPE && c == '>') ret = Location.POST_OBJ;
// Closing typed and language literal.
else if(currLocation == Location.WRITING_OBJ_LITERAL && c == '@') ret = Location.WRITING_LIT_LANG;
else if(currLocation == Location.WRITING_OBJ_LITERAL && c == '^') ret = Location.WRITING_LIT_TYPE;
// Spaces.
else if( c == ' ' &&
(
currLocation == Location.PRE_SUBJECT ||
currLocation == Location.PRE_PRED ||
currLocation == Location.PRE_OBJ ||
currLocation == Location.POST_OBJ
)
) ret = currLocation;
// Reset.
else if(currLocation == Location.POST_OBJ && c == '.') ret = Location.PRE_SUBJECT;
// Error
else ret = Location.ERROR;
currState.location=ret;
}
var untilSpace = function(c) { return c != ' '; };
var untilEndURI = function(c) { return c != '>'; };
return {
startState: function() {
return {
location : Location.PRE_SUBJECT,
uris : [],
anchors : [],
bnodes : [],
langs : [],
types : []
};
},
token: function(stream, state) {
var ch = stream.next();
if(ch == '<') {
transitState(state, ch);
var parsedURI = '';
stream.eatWhile( function(c) { if( c != '#' && c != '>' ) { parsedURI += c; return true; } return false;} );
state.uris.push(parsedURI);
if( stream.match('#', false) ) return 'variable';
stream.next();
transitState(state, '>');
return 'variable';
}
if(ch == '#') {
var parsedAnchor = '';
stream.eatWhile(function(c) { if(c != '>' && c != ' ') { parsedAnchor+= c; return true; } return false;});
state.anchors.push(parsedAnchor);
return 'variable-2';
}
if(ch == '>') {
transitState(state, '>');
return 'variable';
}
if(ch == '_') {
transitState(state, ch);
var parsedBNode = '';
stream.eatWhile(function(c) { if( c != ' ' ) { parsedBNode += c; return true; } return false;});
state.bnodes.push(parsedBNode);
stream.next();
transitState(state, ' ');
return 'builtin';
}
if(ch == '"') {
transitState(state, ch);
stream.eatWhile( function(c) { return c != '"'; } );
stream.next();
if( stream.peek() != '@' && stream.peek() != '^' ) {
transitState(state, '"');
}
return 'string';
}
if( ch == '@' ) {
transitState(state, '@');
var parsedLang = '';
stream.eatWhile(function(c) { if( c != ' ' ) { parsedLang += c; return true; } return false;});
state.langs.push(parsedLang);
stream.next();
transitState(state, ' ');
return 'string-2';
}
if( ch == '^' ) {
stream.next();
transitState(state, '^');
var parsedType = '';
stream.eatWhile(function(c) { if( c != '>' ) { parsedType += c; return true; } return false;} );
state.types.push(parsedType);
stream.next();
transitState(state, '>');
return 'variable';
}
if( ch == ' ' ) {
transitState(state, ch);
}
if( ch == '.' ) {
transitState(state, ch);
}
}
};
});
CodeMirror.defineMIME("text/n-triples", "ntriples");
<!doctype html>
<meta charset=utf-8>
<title>CodeMirror: OCaml mode</title>
<link rel=stylesheet href=../../lib/codemirror.css>
<link rel=stylesheet href=../../doc/docs.css>
<style type=text/css>
.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}
</style>
<script src=../../lib/codemirror.js></script>
<script src=ocaml.js></script>
<h1>CodeMirror: OCaml mode</h1>
<textarea id=code>
(* Summing a list of integers *)
let rec sum xs =
match xs with
| [] -&gt; 0
| x :: xs' -&gt; x + sum xs'
(* Quicksort *)
let rec qsort = function
| [] -&gt; []
| pivot :: rest -&gt;
let is_less x = x &lt; pivot in
let left, right = List.partition is_less rest in
qsort left @ [pivot] @ qsort right
(* Fibonacci Sequence *)
let rec fib_aux n a b =
match n with
| 0 -&gt; a
| _ -&gt; fib_aux (n - 1) (a + b) a
let fib n = fib_aux n 0 1
(* Birthday paradox *)
let year_size = 365.
let rec birthday_paradox prob people =
let prob' = (year_size -. float people) /. year_size *. prob in
if prob' &lt; 0.5 then
Printf.printf "answer = %d\n" (people+1)
else
birthday_paradox prob' (people+1) ;;
birthday_paradox 1.0 1
(* Church numerals *)
let zero f x = x
let succ n f x = f (n f x)
let one = succ zero
let two = succ (succ zero)
let add n1 n2 f x = n1 f (n2 f x)
let to_string n = n (fun k -&gt; "S" ^ k) "0"
let _ = to_string (add (succ two) two)
(* Elementary functions *)
let square x = x * x;;
let rec fact x =
if x &lt;= 1 then 1 else x * fact (x - 1);;
(* Automatic memory management *)
let l = 1 :: 2 :: 3 :: [];;
[1; 2; 3];;
5 :: l;;
(* Polymorphism: sorting lists *)
let rec sort = function
| [] -&gt; []
| x :: l -&gt; insert x (sort l)
and insert elem = function
| [] -&gt; [elem]
| x :: l -&gt;
if elem &lt; x then elem :: x :: l else x :: insert elem l;;
(* Imperative features *)
let add_polynom p1 p2 =
let n1 = Array.length p1
and n2 = Array.length p2 in
let result = Array.create (max n1 n2) 0 in
for i = 0 to n1 - 1 do result.(i) &lt;- p1.(i) done;
for i = 0 to n2 - 1 do result.(i) &lt;- result.(i) + p2.(i) done;
result;;
add_polynom [| 1; 2 |] [| 1; 2; 3 |];;
(* We may redefine fact using a reference cell and a for loop *)
let fact n =
let result = ref 1 in
for i = 2 to n do
result := i * !result
done;
!result;;
fact 5;;
(* Triangle (graphics) *)
let () =
ignore( Glut.init Sys.argv );
Glut.initDisplayMode ~double_buffer:true ();
ignore (Glut.createWindow ~title:"OpenGL Demo");
let angle t = 10. *. t *. t in
let render () =
GlClear.clear [ `color ];
GlMat.load_identity ();
GlMat.rotate ~angle: (angle (Sys.time ())) ~z:1. ();
GlDraw.begins `triangles;
List.iter GlDraw.vertex2 [-1., -1.; 0., 1.; 1., -1.];
GlDraw.ends ();
Glut.swapBuffers () in
GlMat.mode `modelview;
Glut.displayFunc ~cb:render;
Glut.idleFunc ~cb:(Some Glut.postRedisplay);
Glut.mainLoop ()
(* A Hundred Lines of Caml - http://caml.inria.fr/about/taste.en.html *)
(* OCaml page on Wikipedia - http://en.wikipedia.org/wiki/OCaml *)
</textarea>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById('code'), {
mode: 'ocaml',
lineNumbers: true,
matchBrackets: true
});
</script>
<p><strong>MIME types defined:</strong> <code>text/x-ocaml</code>.</p>
CodeMirror.defineMode('ocaml', function(config) {
var words = {
'true': 'atom',
'false': 'atom',
'let': 'keyword',
'rec': 'keyword',
'in': 'keyword',
'of': 'keyword',
'and': 'keyword',
'succ': 'keyword',
'if': 'keyword',
'then': 'keyword',
'else': 'keyword',
'for': 'keyword',
'to': 'keyword',
'while': 'keyword',
'do': 'keyword',
'done': 'keyword',
'fun': 'keyword',
'function': 'keyword',
'val': 'keyword',
'type': 'keyword',
'mutable': 'keyword',
'match': 'keyword',
'with': 'keyword',
'try': 'keyword',
'raise': 'keyword',
'begin': 'keyword',
'end': 'keyword',
'open': 'builtin',
'trace': 'builtin',
'ignore': 'builtin',
'exit': 'builtin',
'print_string': 'builtin',
'print_endline': 'builtin'
};
function tokenBase(stream, state) {
var sol = stream.sol();
var ch = stream.next();
if (ch === '"') {
state.tokenize = tokenString;
return state.tokenize(stream, state);
}
if (ch === '(') {
if (stream.eat('*')) {
state.commentLevel++;
state.tokenize = tokenComment;
return state.tokenize(stream, state);
}
}
if (ch === '~') {
stream.eatWhile(/\w/);
return 'variable-2';
}
if (ch === '`') {
stream.eatWhile(/\w/);
return 'quote';
}
if (/\d/.test(ch)) {
stream.eatWhile(/[\d]/);
if (stream.eat('.')) {
stream.eatWhile(/[\d]/);
}
return 'number';
}
if ( /[+\-*&%=<>!?|]/.test(ch)) {
return 'operator';
}
stream.eatWhile(/\w/);
var cur = stream.current();
return words[cur] || 'variable';
}
function tokenString(stream, state) {
var next, end = false, escaped = false;
while ((next = stream.next()) != null) {
if (next === '"' && !escaped) {
end = true;
break;
}
escaped = !escaped && next === '\\';
}
if (end && !escaped) {
state.tokenize = tokenBase;
}
return 'string';
};
function tokenComment(stream, state) {
var prev, next;
while(state.commentLevel > 0 && (next = stream.next()) != null) {
if (prev === '(' && next === '*') state.commentLevel++;
if (prev === '*' && next === ')') state.commentLevel--;
prev = next;
}
if (state.commentLevel <= 0) {
state.tokenize = tokenBase;
}
return 'comment';
}
return {
startState: function() {return {tokenize: tokenBase, commentLevel: 0};},
token: function(stream, state) {
if (stream.eatSpace()) return null;
return state.tokenize(stream, state);
}
};
});
CodeMirror.defineMIME('text/x-ocaml', 'ocaml');
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Pascal mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="pascal.js"></script>
<link rel="stylesheet" href="../../doc/docs.css">
<style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
</head>
<body>
<h1>CodeMirror: Pascal mode</h1>
<div><textarea id="code" name="code">
(* Example Pascal code *)
while a <> b do writeln('Waiting');
if a > b then
writeln('Condition met')
else
writeln('Condition not met');
for i := 1 to 10 do
writeln('Iteration: ', i:1);
repeat
a := a + 1
until a = 10;
case i of
0: write('zero');
1: write('one');
2: write('two')
end;
</textarea></div>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
matchBrackets: true,
mode: "text/x-pascal"
});
</script>
<p><strong>MIME types defined:</strong> <code>text/x-pascal</code>.</p>
</body>
</html>
Copyright (c) 2011 souceLair <support@sourcelair.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
CodeMirror.defineMode("pascal", 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("and array begin case const div do downto else end file for forward integer " +
"boolean char function goto if in label mod nil not of or packed procedure " +
"program record repeat set string then to type until var while with");
var atoms = {"null": true};
var isOperatorChar = /[+\-*&%=<>!?|\/]/;
function tokenBase(stream, state) {
var ch = stream.next();
if (ch == "#" && state.startOfLine) {
stream.skipToEnd();
return "meta";
}
if (ch == '"' || ch == "'") {
state.tokenize = tokenString(ch);
return state.tokenize(stream, state);
}
if (ch == "(" && stream.eat("*")) {
state.tokenize = tokenComment;
return tokenComment(stream, state);
}
if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
return null;
}
if (/\d/.test(ch)) {
stream.eatWhile(/[\w\.]/);
return "number";
}
if (ch == "/") {
if (stream.eat("/")) {
stream.skipToEnd();
return "comment";
}
}
if (isOperatorChar.test(ch)) {
stream.eatWhile(isOperatorChar);
return "operator";
}
stream.eatWhile(/[\w\$_]/);
var cur = stream.current();
if (keywords.propertyIsEnumerable(cur)) 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 && next == "\\";
}
if (end || !escaped) state.tokenize = null;
return "string";
};
}
function tokenComment(stream, state) {
var maybeEnd = false, ch;
while (ch = stream.next()) {
if (ch == ")" && maybeEnd) {
state.tokenize = null;
break;
}
maybeEnd = (ch == "*");
}
return "comment";
}
// Interface
return {
startState: function(basecolumn) {
return {tokenize: null};
},
token: function(stream, state) {
if (stream.eatSpace()) return null;
var style = (state.tokenize || tokenBase)(stream, state);
if (style == "comment" || style == "meta") return style;
return style;
},
electricChars: "{}"
};
});
CodeMirror.defineMIME("text/x-pascal", "pascal");
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Perl mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="perl.js"></script>
<link rel="stylesheet" href="../../doc/docs.css">
<style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
</head>
<body>
<h1>CodeMirror: Perl mode</h1>
<div><textarea id="code" name="code">
#!/usr/bin/perl
use Something qw(func1 func2);
# strings
my $s1 = qq'single line';
our $s2 = q(multi-
line);
=item Something
Example.
=cut
my $html=<<'HTML'
<html>
<title>hi!</title>
</html>
HTML
print "first,".join(',', 'second', qq~third~);
if($s1 =~ m[(?<!\s)(l.ne)\z]o) {
$h->{$1}=$$.' predefined variables';
$s2 =~ s/\-line//ox;
$s1 =~ s[
line ]
[
block
]ox;
}
1; # numbers and comments
__END__
something...
</textarea></div>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
matchBrackets: true
});
</script>
<p><strong>MIME types defined:</strong> <code>text/x-perl</code>.</p>
</body>
</html>
Copyright (C) 2011 by Sabaca <mail@sabaca.com> under the MIT license.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
// CodeMirror2 mode/perl/perl.js (text/x-perl) beta 0.10 (2011-11-08)
// This is a part of CodeMirror from https://github.com/sabaca/CodeMirror_mode_perl (mail@sabaca.com)
CodeMirror.defineMode("perl",function(config,parserConfig){
// http://perldoc.perl.org
var PERL={ // null - magic touch
// 1 - keyword
// 2 - def
// 3 - atom
// 4 - operator
// 5 - variable-2 (predefined)
// [x,y] - x=1,2,3; y=must be defined if x{...}
// PERL operators
'->' : 4,
'++' : 4,
'--' : 4,
'**' : 4,
// ! ~ \ and unary + and -
'=~' : 4,
'!~' : 4,
'*' : 4,
'/' : 4,
'%' : 4,
'x' : 4,
'+' : 4,
'-' : 4,
'.' : 4,
'<<' : 4,
'>>' : 4,
// named unary operators
'<' : 4,
'>' : 4,
'<=' : 4,
'>=' : 4,
'lt' : 4,
'gt' : 4,
'le' : 4,
'ge' : 4,
'==' : 4,
'!=' : 4,
'<=>' : 4,
'eq' : 4,
'ne' : 4,
'cmp' : 4,
'~~' : 4,
'&' : 4,
'|' : 4,
'^' : 4,
'&&' : 4,
'||' : 4,
'//' : 4,
'..' : 4,
'...' : 4,
'?' : 4,
':' : 4,
'=' : 4,
'+=' : 4,
'-=' : 4,
'*=' : 4, // etc. ???
',' : 4,
'=>' : 4,
'::' : 4,
// list operators (rightward)
'not' : 4,
'and' : 4,
'or' : 4,
'xor' : 4,
// PERL predefined variables (I know, what this is a paranoid idea, but may be needed for people, who learn PERL, and for me as well, ...and may be for you?;)
'BEGIN' : [5,1],
'END' : [5,1],
'PRINT' : [5,1],
'PRINTF' : [5,1],
'GETC' : [5,1],
'READ' : [5,1],
'READLINE' : [5,1],
'DESTROY' : [5,1],
'TIE' : [5,1],
'TIEHANDLE' : [5,1],
'UNTIE' : [5,1],
'STDIN' : 5,
'STDIN_TOP' : 5,
'STDOUT' : 5,
'STDOUT_TOP' : 5,
'STDERR' : 5,
'STDERR_TOP' : 5,
'$ARG' : 5,
'$_' : 5,
'@ARG' : 5,
'@_' : 5,
'$LIST_SEPARATOR' : 5,
'$"' : 5,
'$PROCESS_ID' : 5,
'$PID' : 5,
'$$' : 5,
'$REAL_GROUP_ID' : 5,
'$GID' : 5,
'$(' : 5,
'$EFFECTIVE_GROUP_ID' : 5,
'$EGID' : 5,
'$)' : 5,
'$PROGRAM_NAME' : 5,
'$0' : 5,
'$SUBSCRIPT_SEPARATOR' : 5,
'$SUBSEP' : 5,
'$;' : 5,
'$REAL_USER_ID' : 5,
'$UID' : 5,
'$<' : 5,
'$EFFECTIVE_USER_ID' : 5,
'$EUID' : 5,
'$>' : 5,
'$a' : 5,
'$b' : 5,
'$COMPILING' : 5,
'$^C' : 5,
'$DEBUGGING' : 5,
'$^D' : 5,
'${^ENCODING}' : 5,
'$ENV' : 5,
'%ENV' : 5,
'$SYSTEM_FD_MAX' : 5,
'$^F' : 5,
'@F' : 5,
'${^GLOBAL_PHASE}' : 5,
'$^H' : 5,
'%^H' : 5,
'@INC' : 5,
'%INC' : 5,
'$INPLACE_EDIT' : 5,
'$^I' : 5,
'$^M' : 5,
'$OSNAME' : 5,
'$^O' : 5,
'${^OPEN}' : 5,
'$PERLDB' : 5,
'$^P' : 5,
'$SIG' : 5,
'%SIG' : 5,
'$BASETIME' : 5,
'$^T' : 5,
'${^TAINT}' : 5,
'${^UNICODE}' : 5,
'${^UTF8CACHE}' : 5,
'${^UTF8LOCALE}' : 5,
'$PERL_VERSION' : 5,
'$^V' : 5,
'${^WIN32_SLOPPY_STAT}' : 5,
'$EXECUTABLE_NAME' : 5,
'$^X' : 5,
'$1' : 5, // - regexp $1, $2...
'$MATCH' : 5,
'$&' : 5,
'${^MATCH}' : 5,
'$PREMATCH' : 5,
'$`' : 5,
'${^PREMATCH}' : 5,
'$POSTMATCH' : 5,
"$'" : 5,
'${^POSTMATCH}' : 5,
'$LAST_PAREN_MATCH' : 5,
'$+' : 5,
'$LAST_SUBMATCH_RESULT' : 5,
'$^N' : 5,
'@LAST_MATCH_END' : 5,
'@+' : 5,
'%LAST_PAREN_MATCH' : 5,
'%+' : 5,
'@LAST_MATCH_START' : 5,
'@-' : 5,
'%LAST_MATCH_START' : 5,
'%-' : 5,
'$LAST_REGEXP_CODE_RESULT' : 5,
'$^R' : 5,
'${^RE_DEBUG_FLAGS}' : 5,
'${^RE_TRIE_MAXBUF}' : 5,
'$ARGV' : 5,
'@ARGV' : 5,
'ARGV' : 5,
'ARGVOUT' : 5,
'$OUTPUT_FIELD_SEPARATOR' : 5,
'$OFS' : 5,
'$,' : 5,
'$INPUT_LINE_NUMBER' : 5,
'$NR' : 5,
'$.' : 5,
'$INPUT_RECORD_SEPARATOR' : 5,
'$RS' : 5,
'$/' : 5,
'$OUTPUT_RECORD_SEPARATOR' : 5,
'$ORS' : 5,
'$\\' : 5,
'$OUTPUT_AUTOFLUSH' : 5,
'$|' : 5,
'$ACCUMULATOR' : 5,
'$^A' : 5,
'$FORMAT_FORMFEED' : 5,
'$^L' : 5,
'$FORMAT_PAGE_NUMBER' : 5,
'$%' : 5,
'$FORMAT_LINES_LEFT' : 5,
'$-' : 5,
'$FORMAT_LINE_BREAK_CHARACTERS' : 5,
'$:' : 5,
'$FORMAT_LINES_PER_PAGE' : 5,
'$=' : 5,
'$FORMAT_TOP_NAME' : 5,
'$^' : 5,
'$FORMAT_NAME' : 5,
'$~' : 5,
'${^CHILD_ERROR_NATIVE}' : 5,
'$EXTENDED_OS_ERROR' : 5,
'$^E' : 5,
'$EXCEPTIONS_BEING_CAUGHT' : 5,
'$^S' : 5,
'$WARNING' : 5,
'$^W' : 5,
'${^WARNING_BITS}' : 5,
'$OS_ERROR' : 5,
'$ERRNO' : 5,
'$!' : 5,
'%OS_ERROR' : 5,
'%ERRNO' : 5,
'%!' : 5,
'$CHILD_ERROR' : 5,
'$?' : 5,
'$EVAL_ERROR' : 5,
'$@' : 5,
'$OFMT' : 5,
'$#' : 5,
'$*' : 5,
'$ARRAY_BASE' : 5,
'$[' : 5,
'$OLD_PERL_VERSION' : 5,
'$]' : 5,
// PERL blocks
'if' :[1,1],
elsif :[1,1],
'else' :[1,1],
'while' :[1,1],
unless :[1,1],
'for' :[1,1],
foreach :[1,1],
// PERL functions
'abs' :1, // - absolute value function
accept :1, // - accept an incoming socket connect
alarm :1, // - schedule a SIGALRM
'atan2' :1, // - arctangent of Y/X in the range -PI to PI
bind :1, // - binds an address to a socket
binmode :1, // - prepare binary files for I/O
bless :1, // - create an object
bootstrap :1, //
'break' :1, // - break out of a "given" block
caller :1, // - get context of the current subroutine call
chdir :1, // - change your current working directory
chmod :1, // - changes the permissions on a list of files
chomp :1, // - remove a trailing record separator from a string
chop :1, // - remove the last character from a string
chown :1, // - change the owership on a list of files
chr :1, // - get character this number represents
chroot :1, // - make directory new root for path lookups
close :1, // - close file (or pipe or socket) handle
closedir :1, // - close directory handle
connect :1, // - connect to a remote socket
'continue' :[1,1], // - optional trailing block in a while or foreach
'cos' :1, // - cosine function
crypt :1, // - one-way passwd-style encryption
dbmclose :1, // - breaks binding on a tied dbm file
dbmopen :1, // - create binding on a tied dbm file
'default' :1, //
defined :1, // - test whether a value, variable, or function is defined
'delete' :1, // - deletes a value from a hash
die :1, // - raise an exception or bail out
'do' :1, // - turn a BLOCK into a TERM
dump :1, // - create an immediate core dump
each :1, // - retrieve the next key/value pair from a hash
endgrent :1, // - be done using group file
endhostent :1, // - be done using hosts file
endnetent :1, // - be done using networks file
endprotoent :1, // - be done using protocols file
endpwent :1, // - be done using passwd file
endservent :1, // - be done using services file
eof :1, // - test a filehandle for its end
'eval' :1, // - catch exceptions or compile and run code
'exec' :1, // - abandon this program to run another
exists :1, // - test whether a hash key is present
exit :1, // - terminate this program
'exp' :1, // - raise I to a power
fcntl :1, // - file control system call
fileno :1, // - return file descriptor from filehandle
flock :1, // - lock an entire file with an advisory lock
fork :1, // - create a new process just like this one
format :1, // - declare a picture format with use by the write() function
formline :1, // - internal function used for formats
getc :1, // - get the next character from the filehandle
getgrent :1, // - get next group record
getgrgid :1, // - get group record given group user ID
getgrnam :1, // - get group record given group name
gethostbyaddr :1, // - get host record given its address
gethostbyname :1, // - get host record given name
gethostent :1, // - get next hosts record
getlogin :1, // - return who logged in at this tty
getnetbyaddr :1, // - get network record given its address
getnetbyname :1, // - get networks record given name
getnetent :1, // - get next networks record
getpeername :1, // - find the other end of a socket connection
getpgrp :1, // - get process group
getppid :1, // - get parent process ID
getpriority :1, // - get current nice value
getprotobyname :1, // - get protocol record given name
getprotobynumber :1, // - get protocol record numeric protocol
getprotoent :1, // - get next protocols record
getpwent :1, // - get next passwd record
getpwnam :1, // - get passwd record given user login name
getpwuid :1, // - get passwd record given user ID
getservbyname :1, // - get services record given its name
getservbyport :1, // - get services record given numeric port
getservent :1, // - get next services record
getsockname :1, // - retrieve the sockaddr for a given socket
getsockopt :1, // - get socket options on a given socket
given :1, //
glob :1, // - expand filenames using wildcards
gmtime :1, // - convert UNIX time into record or string using Greenwich time
'goto' :1, // - create spaghetti code
grep :1, // - locate elements in a list test true against a given criterion
hex :1, // - convert a string to a hexadecimal number
'import' :1, // - patch a module's namespace into your own
index :1, // - find a substring within a string
'int' :1, // - get the integer portion of a number
ioctl :1, // - system-dependent device control system call
'join' :1, // - join a list into a string using a separator
keys :1, // - retrieve list of indices from a hash
kill :1, // - send a signal to a process or process group
last :1, // - exit a block prematurely
lc :1, // - return lower-case version of a string
lcfirst :1, // - return a string with just the next letter in lower case
length :1, // - return the number of bytes in a string
'link' :1, // - create a hard link in the filesytem
listen :1, // - register your socket as a server
local : 2, // - create a temporary value for a global variable (dynamic scoping)
localtime :1, // - convert UNIX time into record or string using local time
lock :1, // - get a thread lock on a variable, subroutine, or method
'log' :1, // - retrieve the natural logarithm for a number
lstat :1, // - stat a symbolic link
m :null, // - match a string with a regular expression pattern
map :1, // - apply a change to a list to get back a new list with the changes
mkdir :1, // - create a directory
msgctl :1, // - SysV IPC message control operations
msgget :1, // - get SysV IPC message queue
msgrcv :1, // - receive a SysV IPC message from a message queue
msgsnd :1, // - send a SysV IPC message to a message queue
my : 2, // - declare and assign a local variable (lexical scoping)
'new' :1, //
next :1, // - iterate a block prematurely
no :1, // - unimport some module symbols or semantics at compile time
oct :1, // - convert a string to an octal number
open :1, // - open a file, pipe, or descriptor
opendir :1, // - open a directory
ord :1, // - find a character's numeric representation
our : 2, // - declare and assign a package variable (lexical scoping)
pack :1, // - convert a list into a binary representation
'package' :1, // - declare a separate global namespace
pipe :1, // - open a pair of connected filehandles
pop :1, // - remove the last element from an array and return it
pos :1, // - find or set the offset for the last/next m//g search
print :1, // - output a list to a filehandle
printf :1, // - output a formatted list to a filehandle
prototype :1, // - get the prototype (if any) of a subroutine
push :1, // - append one or more elements to an array
q :null, // - singly quote a string
qq :null, // - doubly quote a string
qr :null, // - Compile pattern
quotemeta :null, // - quote regular expression magic characters
qw :null, // - quote a list of words
qx :null, // - backquote quote a string
rand :1, // - retrieve the next pseudorandom number
read :1, // - fixed-length buffered input from a filehandle
readdir :1, // - get a directory from a directory handle
readline :1, // - fetch a record from a file
readlink :1, // - determine where a symbolic link is pointing
readpipe :1, // - execute a system command and collect standard output
recv :1, // - receive a message over a Socket
redo :1, // - start this loop iteration over again
ref :1, // - find out the type of thing being referenced
rename :1, // - change a filename
require :1, // - load in external functions from a library at runtime
reset :1, // - clear all variables of a given name
'return' :1, // - get out of a function early
reverse :1, // - flip a string or a list
rewinddir :1, // - reset directory handle
rindex :1, // - right-to-left substring search
rmdir :1, // - remove a directory
s :null, // - replace a pattern with a string
say :1, // - print with newline
scalar :1, // - force a scalar context
seek :1, // - reposition file pointer for random-access I/O
seekdir :1, // - reposition directory pointer
select :1, // - reset default output or do I/O multiplexing
semctl :1, // - SysV semaphore control operations
semget :1, // - get set of SysV semaphores
semop :1, // - SysV semaphore operations
send :1, // - send a message over a socket
setgrent :1, // - prepare group file for use
sethostent :1, // - prepare hosts file for use
setnetent :1, // - prepare networks file for use
setpgrp :1, // - set the process group of a process
setpriority :1, // - set a process's nice value
setprotoent :1, // - prepare protocols file for use
setpwent :1, // - prepare passwd file for use
setservent :1, // - prepare services file for use
setsockopt :1, // - set some socket options
shift :1, // - remove the first element of an array, and return it
shmctl :1, // - SysV shared memory operations
shmget :1, // - get SysV shared memory segment identifier
shmread :1, // - read SysV shared memory
shmwrite :1, // - write SysV shared memory
shutdown :1, // - close down just half of a socket connection
'sin' :1, // - return the sine of a number
sleep :1, // - block for some number of seconds
socket :1, // - create a socket
socketpair :1, // - create a pair of sockets
'sort' :1, // - sort a list of values
splice :1, // - add or remove elements anywhere in an array
'split' :1, // - split up a string using a regexp delimiter
sprintf :1, // - formatted print into a string
'sqrt' :1, // - square root function
srand :1, // - seed the random number generator
stat :1, // - get a file's status information
state :1, // - declare and assign a state variable (persistent lexical scoping)
study :1, // - optimize input data for repeated searches
'sub' :1, // - declare a subroutine, possibly anonymously
'substr' :1, // - get or alter a portion of a stirng
symlink :1, // - create a symbolic link to a file
syscall :1, // - execute an arbitrary system call
sysopen :1, // - open a file, pipe, or descriptor
sysread :1, // - fixed-length unbuffered input from a filehandle
sysseek :1, // - position I/O pointer on handle used with sysread and syswrite
system :1, // - run a separate program
syswrite :1, // - fixed-length unbuffered output to a filehandle
tell :1, // - get current seekpointer on a filehandle
telldir :1, // - get current seekpointer on a directory handle
tie :1, // - bind a variable to an object class
tied :1, // - get a reference to the object underlying a tied variable
time :1, // - return number of seconds since 1970
times :1, // - return elapsed time for self and child processes
tr :null, // - transliterate a string
truncate :1, // - shorten a file
uc :1, // - return upper-case version of a string
ucfirst :1, // - return a string with just the next letter in upper case
umask :1, // - set file creation mode mask
undef :1, // - remove a variable or function definition
unlink :1, // - remove one link to a file
unpack :1, // - convert binary structure into normal perl variables
unshift :1, // - prepend more elements to the beginning of a list
untie :1, // - break a tie binding to a variable
use :1, // - load in a module at compile time
utime :1, // - set a file's last access and modify times
values :1, // - return a list of the values in a hash
vec :1, // - test or set particular bits in a string
wait :1, // - wait for any child process to die
waitpid :1, // - wait for a particular child process to die
wantarray :1, // - get void vs scalar vs list context of current subroutine call
warn :1, // - print debugging info
when :1, //
write :1, // - print a picture record
y :null}; // - transliterate a string
var RXstyle="string-2";
var RXmodifiers=/[goseximacplud]/; // NOTE: "m", "s", "y" and "tr" need to correct real modifiers for each regexp type
function tokenChain(stream,state,chain,style,tail){ // NOTE: chain.length > 2 is not working now (it's for s[...][...]geos;)
state.chain=null; // 12 3tail
state.style=null;
state.tail=null;
state.tokenize=function(stream,state){
var e=false,c,i=0;
while(c=stream.next()){
if(c===chain[i]&&!e){
if(chain[++i]!==undefined){
state.chain=chain[i];
state.style=style;
state.tail=tail;}
else if(tail)
stream.eatWhile(tail);
state.tokenize=tokenPerl;
return style;}
e=!e&&c=="\\";}
return style;};
return state.tokenize(stream,state);}
function tokenSOMETHING(stream,state,string){
state.tokenize=function(stream,state){
if(stream.string==string)
state.tokenize=tokenPerl;
stream.skipToEnd();
return "string";};
return state.tokenize(stream,state);}
function tokenPerl(stream,state){
if(stream.eatSpace())
return null;
if(state.chain)
return tokenChain(stream,state,state.chain,state.style,state.tail);
if(stream.match(/^\-?[\d\.]/,false))
if(stream.match(/^(\-?(\d*\.\d+(e[+-]?\d+)?|\d+\.\d*)|0x[\da-fA-F]+|0b[01]+|\d+(e[+-]?\d+)?)/))
return 'number';
if(stream.match(/^<<(?=\w)/)){ // NOTE: <<SOMETHING\n...\nSOMETHING\n
stream.eatWhile(/\w/);
return tokenSOMETHING(stream,state,stream.current().substr(2));}
if(stream.sol()&&stream.match(/^\=item(?!\w)/)){// NOTE: \n=item...\n=cut\n
return tokenSOMETHING(stream,state,'=cut');}
var ch=stream.next();
if(ch=='"'||ch=="'"){ // NOTE: ' or " or <<'SOMETHING'\n...\nSOMETHING\n or <<"SOMETHING"\n...\nSOMETHING\n
if(stream.prefix(3)=="<<"+ch){
var p=stream.pos;
stream.eatWhile(/\w/);
var n=stream.current().substr(1);
if(n&&stream.eat(ch))
return tokenSOMETHING(stream,state,n);
stream.pos=p;}
return tokenChain(stream,state,[ch],"string");}
if(ch=="q"){
var c=stream.look(-2);
if(!(c&&/\w/.test(c))){
c=stream.look(0);
if(c=="x"){
c=stream.look(1);
if(c=="("){
stream.eatSuffix(2);
return tokenChain(stream,state,[")"],RXstyle,RXmodifiers);}
if(c=="["){
stream.eatSuffix(2);
return tokenChain(stream,state,["]"],RXstyle,RXmodifiers);}
if(c=="{"){
stream.eatSuffix(2);
return tokenChain(stream,state,["}"],RXstyle,RXmodifiers);}
if(c=="<"){
stream.eatSuffix(2);
return tokenChain(stream,state,[">"],RXstyle,RXmodifiers);}
if(/[\^'"!~\/]/.test(c)){
stream.eatSuffix(1);
return tokenChain(stream,state,[stream.eat(c)],RXstyle,RXmodifiers);}}
else if(c=="q"){
c=stream.look(1);
if(c=="("){
stream.eatSuffix(2);
return tokenChain(stream,state,[")"],"string");}
if(c=="["){
stream.eatSuffix(2);
return tokenChain(stream,state,["]"],"string");}
if(c=="{"){
stream.eatSuffix(2);
return tokenChain(stream,state,["}"],"string");}
if(c=="<"){
stream.eatSuffix(2);
return tokenChain(stream,state,[">"],"string");}
if(/[\^'"!~\/]/.test(c)){
stream.eatSuffix(1);
return tokenChain(stream,state,[stream.eat(c)],"string");}}
else if(c=="w"){
c=stream.look(1);
if(c=="("){
stream.eatSuffix(2);
return tokenChain(stream,state,[")"],"bracket");}
if(c=="["){
stream.eatSuffix(2);
return tokenChain(stream,state,["]"],"bracket");}
if(c=="{"){
stream.eatSuffix(2);
return tokenChain(stream,state,["}"],"bracket");}
if(c=="<"){
stream.eatSuffix(2);
return tokenChain(stream,state,[">"],"bracket");}
if(/[\^'"!~\/]/.test(c)){
stream.eatSuffix(1);
return tokenChain(stream,state,[stream.eat(c)],"bracket");}}
else if(c=="r"){
c=stream.look(1);
if(c=="("){
stream.eatSuffix(2);
return tokenChain(stream,state,[")"],RXstyle,RXmodifiers);}
if(c=="["){
stream.eatSuffix(2);
return tokenChain(stream,state,["]"],RXstyle,RXmodifiers);}
if(c=="{"){
stream.eatSuffix(2);
return tokenChain(stream,state,["}"],RXstyle,RXmodifiers);}
if(c=="<"){
stream.eatSuffix(2);
return tokenChain(stream,state,[">"],RXstyle,RXmodifiers);}
if(/[\^'"!~\/]/.test(c)){
stream.eatSuffix(1);
return tokenChain(stream,state,[stream.eat(c)],RXstyle,RXmodifiers);}}
else if(/[\^'"!~\/(\[{<]/.test(c)){
if(c=="("){
stream.eatSuffix(1);
return tokenChain(stream,state,[")"],"string");}
if(c=="["){
stream.eatSuffix(1);
return tokenChain(stream,state,["]"],"string");}
if(c=="{"){
stream.eatSuffix(1);
return tokenChain(stream,state,["}"],"string");}
if(c=="<"){
stream.eatSuffix(1);
return tokenChain(stream,state,[">"],"string");}
if(/[\^'"!~\/]/.test(c)){
return tokenChain(stream,state,[stream.eat(c)],"string");}}}}
if(ch=="m"){
var c=stream.look(-2);
if(!(c&&/\w/.test(c))){
c=stream.eat(/[(\[{<\^'"!~\/]/);
if(c){
if(/[\^'"!~\/]/.test(c)){
return tokenChain(stream,state,[c],RXstyle,RXmodifiers);}
if(c=="("){
return tokenChain(stream,state,[")"],RXstyle,RXmodifiers);}
if(c=="["){
return tokenChain(stream,state,["]"],RXstyle,RXmodifiers);}
if(c=="{"){
return tokenChain(stream,state,["}"],RXstyle,RXmodifiers);}
if(c=="<"){
return tokenChain(stream,state,[">"],RXstyle,RXmodifiers);}}}}
if(ch=="s"){
var c=/[\/>\]})\w]/.test(stream.look(-2));
if(!c){
c=stream.eat(/[(\[{<\^'"!~\/]/);
if(c){
if(c=="[")
return tokenChain(stream,state,["]","]"],RXstyle,RXmodifiers);
if(c=="{")
return tokenChain(stream,state,["}","}"],RXstyle,RXmodifiers);
if(c=="<")
return tokenChain(stream,state,[">",">"],RXstyle,RXmodifiers);
if(c=="(")
return tokenChain(stream,state,[")",")"],RXstyle,RXmodifiers);
return tokenChain(stream,state,[c,c],RXstyle,RXmodifiers);}}}
if(ch=="y"){
var c=/[\/>\]})\w]/.test(stream.look(-2));
if(!c){
c=stream.eat(/[(\[{<\^'"!~\/]/);
if(c){
if(c=="[")
return tokenChain(stream,state,["]","]"],RXstyle,RXmodifiers);
if(c=="{")
return tokenChain(stream,state,["}","}"],RXstyle,RXmodifiers);
if(c=="<")
return tokenChain(stream,state,[">",">"],RXstyle,RXmodifiers);
if(c=="(")
return tokenChain(stream,state,[")",")"],RXstyle,RXmodifiers);
return tokenChain(stream,state,[c,c],RXstyle,RXmodifiers);}}}
if(ch=="t"){
var c=/[\/>\]})\w]/.test(stream.look(-2));
if(!c){
c=stream.eat("r");if(c){
c=stream.eat(/[(\[{<\^'"!~\/]/);
if(c){
if(c=="[")
return tokenChain(stream,state,["]","]"],RXstyle,RXmodifiers);
if(c=="{")
return tokenChain(stream,state,["}","}"],RXstyle,RXmodifiers);
if(c=="<")
return tokenChain(stream,state,[">",">"],RXstyle,RXmodifiers);
if(c=="(")
return tokenChain(stream,state,[")",")"],RXstyle,RXmodifiers);
return tokenChain(stream,state,[c,c],RXstyle,RXmodifiers);}}}}
if(ch=="`"){
return tokenChain(stream,state,[ch],"variable-2");}
if(ch=="/"){
if(!/~\s*$/.test(stream.prefix()))
return "operator";
else
return tokenChain(stream,state,[ch],RXstyle,RXmodifiers);}
if(ch=="$"){
var p=stream.pos;
if(stream.eatWhile(/\d/)||stream.eat("{")&&stream.eatWhile(/\d/)&&stream.eat("}"))
return "variable-2";
else
stream.pos=p;}
if(/[$@%]/.test(ch)){
var p=stream.pos;
if(stream.eat("^")&&stream.eat(/[A-Z]/)||!/[@$%&]/.test(stream.look(-2))&&stream.eat(/[=|\\\-#?@;:&`~\^!\[\]*'"$+.,\/<>()]/)){
var c=stream.current();
if(PERL[c])
return "variable-2";}
stream.pos=p;}
if(/[$@%&]/.test(ch)){
if(stream.eatWhile(/[\w$\[\]]/)||stream.eat("{")&&stream.eatWhile(/[\w$\[\]]/)&&stream.eat("}")){
var c=stream.current();
if(PERL[c])
return "variable-2";
else
return "variable";}}
if(ch=="#"){
if(stream.look(-2)!="$"){
stream.skipToEnd();
return "comment";}}
if(/[:+\-\^*$&%@=<>!?|\/~\.]/.test(ch)){
var p=stream.pos;
stream.eatWhile(/[:+\-\^*$&%@=<>!?|\/~\.]/);
if(PERL[stream.current()])
return "operator";
else
stream.pos=p;}
if(ch=="_"){
if(stream.pos==1){
if(stream.suffix(6)=="_END__"){
return tokenChain(stream,state,['\0'],"comment");}
else if(stream.suffix(7)=="_DATA__"){
return tokenChain(stream,state,['\0'],"variable-2");}
else if(stream.suffix(7)=="_C__"){
return tokenChain(stream,state,['\0'],"string");}}}
if(/\w/.test(ch)){
var p=stream.pos;
if(stream.look(-2)=="{"&&(stream.look(0)=="}"||stream.eatWhile(/\w/)&&stream.look(0)=="}"))
return "string";
else
stream.pos=p;}
if(/[A-Z]/.test(ch)){
var l=stream.look(-2);
var p=stream.pos;
stream.eatWhile(/[A-Z_]/);
if(/[\da-z]/.test(stream.look(0))){
stream.pos=p;}
else{
var c=PERL[stream.current()];
if(!c)
return "meta";
if(c[1])
c=c[0];
if(l!=":"){
if(c==1)
return "keyword";
else if(c==2)
return "def";
else if(c==3)
return "atom";
else if(c==4)
return "operator";
else if(c==5)
return "variable-2";
else
return "meta";}
else
return "meta";}}
if(/[a-zA-Z_]/.test(ch)){
var l=stream.look(-2);
stream.eatWhile(/\w/);
var c=PERL[stream.current()];
if(!c)
return "meta";
if(c[1])
c=c[0];
if(l!=":"){
if(c==1)
return "keyword";
else if(c==2)
return "def";
else if(c==3)
return "atom";
else if(c==4)
return "operator";
else if(c==5)
return "variable-2";
else
return "meta";}
else
return "meta";}
return null;}
return{
startState:function(){
return{
tokenize:tokenPerl,
chain:null,
style:null,
tail:null};},
token:function(stream,state){
return (state.tokenize||tokenPerl)(stream,state);},
electricChars:"{}"};});
CodeMirror.defineMIME("text/x-perl", "perl");
// it's like "peek", but need for look-ahead or look-behind if index < 0
CodeMirror.StringStream.prototype.look=function(c){
return this.string.charAt(this.pos+(c||0));};
// return a part of prefix of current stream from current position
CodeMirror.StringStream.prototype.prefix=function(c){
if(c){
var x=this.pos-c;
return this.string.substr((x>=0?x:0),c);}
else{
return this.string.substr(0,this.pos-1);}};
// return a part of suffix of current stream from current position
CodeMirror.StringStream.prototype.suffix=function(c){
var y=this.string.length;
var x=y-this.pos+1;
return this.string.substr(this.pos,(c&&c<y?c:x));};
// return a part of suffix of current stream from current position and change current position
CodeMirror.StringStream.prototype.nsuffix=function(c){
var p=this.pos;
var l=c||(this.string.length-this.pos+1);
this.pos+=l;
return this.string.substr(p,l);};
// eating and vomiting a part of stream from current position
CodeMirror.StringStream.prototype.eatSuffix=function(c){
var x=this.pos+c;
var y;
if(x<=0)
this.pos=0;
else if(x>=(y=this.string.length-1))
this.pos=y;
else
this.pos=x;};
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: PHP mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="../xml/xml.js"></script>
<script src="../javascript/javascript.js"></script>
<script src="../css/css.js"></script>
<script src="../clike/clike.js"></script>
<script src="php.js"></script>
<style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
<link rel="stylesheet" href="../../doc/docs.css">
</head>
<body>
<h1>CodeMirror: PHP mode</h1>
<form><textarea id="code" name="code">
<?php
function hello($who) {
return "Hello " . $who;
}
?>
<p>The program says <?= hello("World") ?>.</p>
<script>
alert("And here is some JS code"); // also colored
</script>
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
matchBrackets: true,
mode: "application/x-httpd-php",
indentUnit: 4,
indentWithTabs: true,
enterMode: "keep",
tabMode: "shift"
});
</script>
<p>Simple HTML/PHP mode based on
the <a href="../clike/">C-like</a> mode. Depends on XML,
JavaScript, CSS, and C-like modes.</p>
<p><strong>MIME types defined:</strong> <code>application/x-httpd-php</code> (HTML with PHP code), <code>text/x-php</code> (plain, non-wrapped PHP code).</p>
</body>
</html>
(function() {
function keywords(str) {
var obj = {}, words = str.split(" ");
for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
return obj;
}
function heredoc(delim) {
return function(stream, state) {
if (stream.match(delim)) state.tokenize = null;
else stream.skipToEnd();
return "string";
};
}
var phpConfig = {
name: "clike",
keywords: keywords("abstract and array as break case catch class clone const continue declare default " +
"do else elseif enddeclare endfor endforeach endif endswitch endwhile extends final " +
"for foreach function global goto if implements interface instanceof namespace " +
"new or private protected public static switch throw trait try use var while xor " +
"die echo empty exit eval include include_once isset list require require_once return " +
"print unset __halt_compiler self static parent"),
blockKeywords: keywords("catch do else elseif for foreach if switch try while"),
atoms: keywords("true false null TRUE FALSE NULL"),
multiLineStrings: true,
hooks: {
"$": function(stream, state) {
stream.eatWhile(/[\w\$_]/);
return "variable-2";
},
"<": function(stream, state) {
if (stream.match(/<</)) {
stream.eatWhile(/[\w\.]/);
state.tokenize = heredoc(stream.current().slice(3));
return state.tokenize(stream, state);
}
return false;
},
"#": function(stream, state) {
while (!stream.eol() && !stream.match("?>", false)) stream.next();
return "comment";
},
"/": function(stream, state) {
if (stream.eat("/")) {
while (!stream.eol() && !stream.match("?>", false)) stream.next();
return "comment";
}
return false;
}
}
};
CodeMirror.defineMode("php", function(config, parserConfig) {
var htmlMode = CodeMirror.getMode(config, {name: "xml", htmlMode: true});
var jsMode = CodeMirror.getMode(config, "javascript");
var cssMode = CodeMirror.getMode(config, "css");
var phpMode = CodeMirror.getMode(config, phpConfig);
function dispatch(stream, state) { // TODO open PHP inside text/css
var isPHP = state.curMode == phpMode;
if (stream.sol() && state.pending != '"') state.pending = null;
if (state.curMode == htmlMode) {
if (stream.match(/^<\?\w*/)) {
state.curMode = phpMode;
state.curState = state.php;
state.curClose = "?>";
return "meta";
}
if (state.pending == '"') {
while (!stream.eol() && stream.next() != '"') {}
var style = "string";
} else if (state.pending && stream.pos < state.pending.end) {
stream.pos = state.pending.end;
var style = state.pending.style;
} else {
var style = htmlMode.token(stream, state.curState);
}
state.pending = null;
var cur = stream.current(), openPHP = cur.search(/<\?/);
if (openPHP != -1) {
if (style == "string" && /\"$/.test(cur) && !/\?>/.test(cur)) state.pending = '"';
else state.pending = {end: stream.pos, style: style};
stream.backUp(cur.length - openPHP);
} else if (style == "tag" && stream.current() == ">" && state.curState.context) {
if (/^script$/i.test(state.curState.context.tagName)) {
state.curMode = jsMode;
state.curState = jsMode.startState(htmlMode.indent(state.curState, ""));
state.curClose = /^<\/\s*script\s*>/i;
}
else if (/^style$/i.test(state.curState.context.tagName)) {
state.curMode = cssMode;
state.curState = cssMode.startState(htmlMode.indent(state.curState, ""));
state.curClose = /^<\/\s*style\s*>/i;
}
}
return style;
} else if ((!isPHP || state.php.tokenize == null) &&
stream.match(state.curClose, isPHP)) {
state.curMode = htmlMode;
state.curState = state.html;
state.curClose = null;
if (isPHP) return "meta";
else return dispatch(stream, state);
} else {
return state.curMode.token(stream, state.curState);
}
}
return {
startState: function() {
var html = htmlMode.startState();
return {html: html,
php: phpMode.startState(),
curMode: parserConfig.startOpen ? phpMode : htmlMode,
curState: parserConfig.startOpen ? phpMode.startState() : html,
curClose: parserConfig.startOpen ? /^\?>/ : null,
mode: parserConfig.startOpen ? "php" : "html",
pending: null};
},
copyState: function(state) {
var html = state.html, htmlNew = CodeMirror.copyState(htmlMode, html),
php = state.php, phpNew = CodeMirror.copyState(phpMode, php), cur;
if (state.curState == html) cur = htmlNew;
else if (state.curState == php) cur = phpNew;
else cur = CodeMirror.copyState(state.curMode, state.curState);
return {html: htmlNew, php: phpNew, curMode: state.curMode, curState: cur,
curClose: state.curClose, mode: state.mode,
pending: state.pending};
},
token: dispatch,
indent: function(state, textAfter) {
if ((state.curMode != phpMode && /^\s*<\//.test(textAfter)) ||
(state.curMode == phpMode && /^\?>/.test(textAfter)))
return htmlMode.indent(state.html, textAfter);
return state.curMode.indent(state.curState, textAfter);
},
electricChars: "/{}:",
innerMode: function(state) { return {state: state.curState, mode: state.curMode}; }
};
}, "xml", "clike", "javascript", "css");
CodeMirror.defineMIME("application/x-httpd-php", "php");
CodeMirror.defineMIME("application/x-httpd-php-open", {name: "php", startOpen: true});
CodeMirror.defineMIME("text/x-php", phpConfig);
})();
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Pig Latin mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="pig.js"></script>
<link rel="stylesheet" href="../../doc/docs.css">
<style>.CodeMirror {border: 2px inset #dee;}</style>
</head>
<body>
<h1>CodeMirror: Pig Latin mode</h1>
<form><textarea id="code" name="code">
-- Apache Pig (Pig Latin Language) Demo
/*
This is a multiline comment.
*/
a = LOAD "\path\to\input" USING PigStorage('\t') AS (x:long, y:chararray, z:bytearray);
b = GROUP a BY (x,y,3+4);
c = FOREACH b GENERATE flatten(group) as (x,y), SUM(group.$2) as z;
STORE c INTO "\path\to\output";
--
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
matchBrackets: true,
indentUnit: 4,
mode: "text/x-pig"
});
</script>
<p>
Simple mode that handles Pig Latin language.
</p>
<p><strong>MIME type defined:</strong> <code>text/x-pig</code>
(PIG code)
</html>
/*
* Pig Latin Mode for CodeMirror 2
* @author Prasanth Jayachandran
* @link https://github.com/prasanthj/pig-codemirror-2
* This implementation is adapted from PL/SQL mode in CodeMirror 2.
*/
CodeMirror.defineMode("pig", function(config, parserConfig) {
var indentUnit = config.indentUnit,
keywords = parserConfig.keywords,
builtins = parserConfig.builtins,
types = parserConfig.types,
multiLineStrings = parserConfig.multiLineStrings;
var isOperatorChar = /[*+\-%<>=&?:\/!|]/;
function chain(stream, state, f) {
state.tokenize = f;
return f(stream, state);
}
var type;
function ret(tp, style) {
type = tp;
return style;
}
function tokenComment(stream, state) {
var isEnd = false;
var ch;
while(ch = stream.next()) {
if(ch == "/" && isEnd) {
state.tokenize = tokenBase;
break;
}
isEnd = (ch == "*");
}
return ret("comment", "comment");
}
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 && next == "\\";
}
if (end || !(escaped || multiLineStrings))
state.tokenize = tokenBase;
return ret("string", "error");
};
}
function tokenBase(stream, state) {
var ch = stream.next();
// is a start of string?
if (ch == '"' || ch == "'")
return chain(stream, state, tokenString(ch));
// is it one of the special chars
else if(/[\[\]{}\(\),;\.]/.test(ch))
return ret(ch);
// is it a number?
else if(/\d/.test(ch)) {
stream.eatWhile(/[\w\.]/);
return ret("number", "number");
}
// multi line comment or operator
else if (ch == "/") {
if (stream.eat("*")) {
return chain(stream, state, tokenComment);
}
else {
stream.eatWhile(isOperatorChar);
return ret("operator", "operator");
}
}
// single line comment or operator
else if (ch=="-") {
if(stream.eat("-")){
stream.skipToEnd();
return ret("comment", "comment");
}
else {
stream.eatWhile(isOperatorChar);
return ret("operator", "operator");
}
}
// is it an operator
else if (isOperatorChar.test(ch)) {
stream.eatWhile(isOperatorChar);
return ret("operator", "operator");
}
else {
// get the while word
stream.eatWhile(/[\w\$_]/);
// is it one of the listed keywords?
if (keywords && keywords.propertyIsEnumerable(stream.current().toUpperCase())) {
if (stream.eat(")") || stream.eat(".")) {
//keywords can be used as variables like flatten(group), group.$0 etc..
}
else {
return ("keyword", "keyword");
}
}
// is it one of the builtin functions?
if (builtins && builtins.propertyIsEnumerable(stream.current().toUpperCase()))
{
return ("keyword", "variable-2");
}
// is it one of the listed types?
if (types && types.propertyIsEnumerable(stream.current().toUpperCase()))
return ("keyword", "variable-3");
// default is a 'variable'
return ret("variable", "pig-word");
}
}
// Interface
return {
startState: function(basecolumn) {
return {
tokenize: tokenBase,
startOfLine: true
};
},
token: function(stream, state) {
if(stream.eatSpace()) return null;
var style = state.tokenize(stream, state);
return style;
}
};
});
(function() {
function keywords(str) {
var obj = {}, words = str.split(" ");
for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
return obj;
}
// builtin funcs taken from trunk revision 1303237
var pBuiltins = "ABS ACOS ARITY ASIN ATAN AVG BAGSIZE BINSTORAGE BLOOM BUILDBLOOM CBRT CEIL "
+ "CONCAT COR COS COSH COUNT COUNT_STAR COV CONSTANTSIZE CUBEDIMENSIONS DIFF DISTINCT DOUBLEABS "
+ "DOUBLEAVG DOUBLEBASE DOUBLEMAX DOUBLEMIN DOUBLEROUND DOUBLESUM EXP FLOOR FLOATABS FLOATAVG "
+ "FLOATMAX FLOATMIN FLOATROUND FLOATSUM GENERICINVOKER INDEXOF INTABS INTAVG INTMAX INTMIN "
+ "INTSUM INVOKEFORDOUBLE INVOKEFORFLOAT INVOKEFORINT INVOKEFORLONG INVOKEFORSTRING INVOKER "
+ "ISEMPTY JSONLOADER JSONMETADATA JSONSTORAGE LAST_INDEX_OF LCFIRST LOG LOG10 LOWER LONGABS "
+ "LONGAVG LONGMAX LONGMIN LONGSUM MAX MIN MAPSIZE MONITOREDUDF NONDETERMINISTIC OUTPUTSCHEMA "
+ "PIGSTORAGE PIGSTREAMING RANDOM REGEX_EXTRACT REGEX_EXTRACT_ALL REPLACE ROUND SIN SINH SIZE "
+ "SQRT STRSPLIT SUBSTRING SUM STRINGCONCAT STRINGMAX STRINGMIN STRINGSIZE TAN TANH TOBAG "
+ "TOKENIZE TOMAP TOP TOTUPLE TRIM TEXTLOADER TUPLESIZE UCFIRST UPPER UTF8STORAGECONVERTER ";
// taken from QueryLexer.g
var pKeywords = "VOID IMPORT RETURNS DEFINE LOAD FILTER FOREACH ORDER CUBE DISTINCT COGROUP "
+ "JOIN CROSS UNION SPLIT INTO IF OTHERWISE ALL AS BY USING INNER OUTER ONSCHEMA PARALLEL "
+ "PARTITION GROUP AND OR NOT GENERATE FLATTEN ASC DESC IS STREAM THROUGH STORE MAPREDUCE "
+ "SHIP CACHE INPUT OUTPUT STDERROR STDIN STDOUT LIMIT SAMPLE LEFT RIGHT FULL EQ GT LT GTE LTE "
+ "NEQ MATCHES TRUE FALSE ";
// data types
var pTypes = "BOOLEAN INT LONG FLOAT DOUBLE CHARARRAY BYTEARRAY BAG TUPLE MAP ";
CodeMirror.defineMIME("text/x-pig", {
name: "pig",
builtins: keywords(pBuiltins),
keywords: keywords(pKeywords),
types: keywords(pTypes)
});
}());
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Oracle PL/SQL mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="plsql.js"></script>
<link rel="stylesheet" href="../../doc/docs.css">
<style>.CodeMirror {border: 2px inset #dee;}</style>
</head>
<body>
<h1>CodeMirror: Oracle PL/SQL mode</h1>
<form><textarea id="code" name="code">
-- Oracle PL/SQL Code Demo
/*
based on c-like mode, adapted to PL/SQL by Peter Raganitsch ( http://www.oracle-and-apex.com/ )
April 2011
*/
DECLARE
vIdx NUMBER;
vString VARCHAR2(100);
cText CONSTANT VARCHAR2(100) := 'That''s it! Have fun with CodeMirror 2';
BEGIN
vIdx := 0;
--
FOR rDATA IN
( SELECT *
FROM EMP
ORDER BY EMPNO
)
LOOP
vIdx := vIdx + 1;
vString := rDATA.EMPNO || ' - ' || rDATA.ENAME;
--
UPDATE EMP
SET SAL = SAL * 101/100
WHERE EMPNO = rDATA.EMPNO
;
END LOOP;
--
SYS.DBMS_OUTPUT.Put_Line (cText);
END;
--
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
matchBrackets: true,
indentUnit: 4,
mode: "text/x-plsql"
});
</script>
<p>
Simple mode that handles Oracle PL/SQL language (and Oracle SQL, of course).
</p>
<p><strong>MIME type defined:</strong> <code>text/x-plsql</code>
(PLSQL code)
</html>
CodeMirror.defineMode("plsql", function(config, parserConfig) {
var indentUnit = config.indentUnit,
keywords = parserConfig.keywords,
functions = parserConfig.functions,
types = parserConfig.types,
sqlplus = parserConfig.sqlplus,
multiLineStrings = parserConfig.multiLineStrings;
var isOperatorChar = /[+\-*&%=<>!?:\/|]/;
function chain(stream, state, f) {
state.tokenize = f;
return f(stream, state);
}
var type;
function ret(tp, style) {
type = tp;
return style;
}
function tokenBase(stream, state) {
var ch = stream.next();
// start of string?
if (ch == '"' || ch == "'")
return chain(stream, state, tokenString(ch));
// is it one of the special signs []{}().,;? Seperator?
else if (/[\[\]{}\(\),;\.]/.test(ch))
return ret(ch);
// start of a number value?
else if (/\d/.test(ch)) {
stream.eatWhile(/[\w\.]/);
return ret("number", "number");
}
// multi line comment or simple operator?
else if (ch == "/") {
if (stream.eat("*")) {
return chain(stream, state, tokenComment);
}
else {
stream.eatWhile(isOperatorChar);
return ret("operator", "operator");
}
}
// single line comment or simple operator?
else if (ch == "-") {
if (stream.eat("-")) {
stream.skipToEnd();
return ret("comment", "comment");
}
else {
stream.eatWhile(isOperatorChar);
return ret("operator", "operator");
}
}
// pl/sql variable?
else if (ch == "@" || ch == "$") {
stream.eatWhile(/[\w\d\$_]/);
return ret("word", "variable");
}
// is it a operator?
else if (isOperatorChar.test(ch)) {
stream.eatWhile(isOperatorChar);
return ret("operator", "operator");
}
else {
// get the whole word
stream.eatWhile(/[\w\$_]/);
// is it one of the listed keywords?
if (keywords && keywords.propertyIsEnumerable(stream.current().toLowerCase())) return ret("keyword", "keyword");
// is it one of the listed functions?
if (functions && functions.propertyIsEnumerable(stream.current().toLowerCase())) return ret("keyword", "builtin");
// is it one of the listed types?
if (types && types.propertyIsEnumerable(stream.current().toLowerCase())) return ret("keyword", "variable-2");
// is it one of the listed sqlplus keywords?
if (sqlplus && sqlplus.propertyIsEnumerable(stream.current().toLowerCase())) return ret("keyword", "variable-3");
// default: just a "variable"
return ret("word", "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 && next == "\\";
}
if (end || !(escaped || multiLineStrings))
state.tokenize = tokenBase;
return ret("string", "plsql-string");
};
}
function tokenComment(stream, state) {
var maybeEnd = false, ch;
while (ch = stream.next()) {
if (ch == "/" && maybeEnd) {
state.tokenize = tokenBase;
break;
}
maybeEnd = (ch == "*");
}
return ret("comment", "plsql-comment");
}
// Interface
return {
startState: function(basecolumn) {
return {
tokenize: tokenBase,
startOfLine: true
};
},
token: function(stream, state) {
if (stream.eatSpace()) return null;
var style = state.tokenize(stream, state);
return style;
}
};
});
(function() {
function keywords(str) {
var obj = {}, words = str.split(" ");
for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
return obj;
}
var cKeywords = "abort accept access add all alter and any array arraylen as asc assert assign at attributes audit " +
"authorization avg " +
"base_table begin between binary_integer body boolean by " +
"case cast char char_base check close cluster clusters colauth column comment commit compress connect " +
"connected constant constraint crash create current currval cursor " +
"data_base database date dba deallocate debugoff debugon decimal declare default definition delay delete " +
"desc digits dispose distinct do drop " +
"else elsif enable end entry escape exception exception_init exchange exclusive exists exit external " +
"fast fetch file for force form from function " +
"generic goto grant group " +
"having " +
"identified if immediate in increment index indexes indicator initial initrans insert interface intersect " +
"into is " +
"key " +
"level library like limited local lock log logging long loop " +
"master maxextents maxtrans member minextents minus mislabel mode modify multiset " +
"new next no noaudit nocompress nologging noparallel not nowait number_base " +
"object of off offline on online only open option or order out " +
"package parallel partition pctfree pctincrease pctused pls_integer positive positiven pragma primary prior " +
"private privileges procedure public " +
"raise range raw read rebuild record ref references refresh release rename replace resource restrict return " +
"returning reverse revoke rollback row rowid rowlabel rownum rows run " +
"savepoint schema segment select separate session set share snapshot some space split sql start statement " +
"storage subtype successful synonym " +
"tabauth table tables tablespace task terminate then to trigger truncate type " +
"union unique unlimited unrecoverable unusable update use using " +
"validate value values variable view views " +
"when whenever where while with work";
var cFunctions = "abs acos add_months ascii asin atan atan2 average " +
"bfilename " +
"ceil chartorowid chr concat convert cos cosh count " +
"decode deref dual dump dup_val_on_index " +
"empty error exp " +
"false floor found " +
"glb greatest " +
"hextoraw " +
"initcap instr instrb isopen " +
"last_day least lenght lenghtb ln lower lpad ltrim lub " +
"make_ref max min mod months_between " +
"new_time next_day nextval nls_charset_decl_len nls_charset_id nls_charset_name nls_initcap nls_lower " +
"nls_sort nls_upper nlssort no_data_found notfound null nvl " +
"others " +
"power " +
"rawtohex reftohex round rowcount rowidtochar rpad rtrim " +
"sign sin sinh soundex sqlcode sqlerrm sqrt stddev substr substrb sum sysdate " +
"tan tanh to_char to_date to_label to_multi_byte to_number to_single_byte translate true trunc " +
"uid upper user userenv " +
"variance vsize";
var cTypes = "bfile blob " +
"character clob " +
"dec " +
"float " +
"int integer " +
"mlslabel " +
"natural naturaln nchar nclob number numeric nvarchar2 " +
"real rowtype " +
"signtype smallint string " +
"varchar varchar2";
var cSqlplus = "appinfo arraysize autocommit autoprint autorecovery autotrace " +
"blockterminator break btitle " +
"cmdsep colsep compatibility compute concat copycommit copytypecheck " +
"define describe " +
"echo editfile embedded escape exec execute " +
"feedback flagger flush " +
"heading headsep " +
"instance " +
"linesize lno loboffset logsource long longchunksize " +
"markup " +
"native newpage numformat numwidth " +
"pagesize pause pno " +
"recsep recsepchar release repfooter repheader " +
"serveroutput shiftinout show showmode size spool sqlblanklines sqlcase sqlcode sqlcontinue sqlnumber " +
"sqlpluscompatibility sqlprefix sqlprompt sqlterminator suffix " +
"tab term termout time timing trimout trimspool ttitle " +
"underline " +
"verify version " +
"wrap";
CodeMirror.defineMIME("text/x-plsql", {
name: "plsql",
keywords: keywords(cKeywords),
functions: keywords(cFunctions),
types: keywords(cTypes),
sqlplus: keywords(cSqlplus)
});
}());
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Properties files mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="properties.js"></script>
<style>.CodeMirror {border-top: 1px solid #ddd; border-bottom: 1px solid #ddd;}</style>
<link rel="stylesheet" href="../../doc/docs.css">
</head>
<body>
<h1>CodeMirror: Properties files mode</h1>
<form><textarea id="code" name="code">
# This is a properties file
a.key = A value
another.key = http://example.com
! Exclamation mark as comment
but.not=Within ! A value # indeed
# Spaces at the beginning of a line
spaces.before.key=value
backslash=Used for multi\
line entries,\
that's convenient.
# Unicode sequences
unicode.key=This is \u0020 Unicode
no.multiline=here
# Colons
colons : can be used too
# Spaces
spaces\ in\ keys=Not very common...
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
</script>
<p><strong>MIME types defined:</strong> <code>text/x-properties</code>,
<code>text/x-ini</code>.</p>
</body>
</html>
CodeMirror.defineMode("properties", function() {
return {
token: function(stream, state) {
var sol = stream.sol() || state.afterSection;
var eol = stream.eol();
state.afterSection = false;
if (sol) {
if (state.nextMultiline) {
state.inMultiline = true;
state.nextMultiline = false;
} else {
state.position = "def";
}
}
if (eol && ! state.nextMultiline) {
state.inMultiline = false;
state.position = "def";
}
if (sol) {
while(stream.eatSpace());
}
var ch = stream.next();
if (sol && (ch === "#" || ch === "!" || ch === ";")) {
state.position = "comment";
stream.skipToEnd();
return "comment";
} else if (sol && ch === "[") {
state.afterSection = true;
stream.skipTo("]"); stream.eat("]");
return "header";
} else if (ch === "=" || ch === ":") {
state.position = "quote";
return null;
} else if (ch === "\\" && state.position === "quote") {
if (stream.next() !== "u") { // u = Unicode sequence \u1234
// Multiline value
state.nextMultiline = true;
}
}
return state.position;
},
startState: function() {
return {
position : "def", // Current position, "def", "quote" or "comment"
nextMultiline : false, // Is the next line multiline value
inMultiline : false, // Is the current line a multiline value
afterSection : false // Did we just open a section
};
}
};
});
CodeMirror.defineMIME("text/x-properties", "properties");
CodeMirror.defineMIME("text/x-ini", "properties");
The MIT License
Copyright (c) 2010 Timothy Farrell
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

CodeMirror Build Status

CodeMirror is a JavaScript component that provides a code editor in the browser. When a mode is available for the language you are coding in, it will color your code, and optionally help with indentation.

The project page is http://codemirror.net The manual is at http://codemirror.net/doc/manual.html

This file has been truncated, but you can view the full file.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Python mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="python.js"></script>
<link rel="stylesheet" href="../../doc/docs.css">
<style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
</head>
<body>
<h1>CodeMirror: Python mode</h1>
<div><textarea id="code" name="code">
# Literals
1234
0.0e101
.123
0b01010011100
0o01234567
0x0987654321abcdef
7
2147483647
3L
79228162514264337593543950336L
0x100000000L
79228162514264337593543950336
0xdeadbeef
3.14j
10.j
10j
.001j
1e100j
3.14e-10j
# String Literals
'For\''
"God\""
"""so loved
the world"""
'''that he gave
his only begotten\' '''
'that whosoever believeth \
in him'
''
# Identifiers
__a__
a.b
a.b.c
# Operators
+ - * / % & | ^ ~ < >
== != <= >= <> << >> // **
and or not in is
# Delimiters
() [] {} , : ` = ; @ . # Note that @ and . require the proper context.
+= -= *= /= %= &= |= ^=
//= >>= <<= **=
# Keywords
as assert break class continue def del elif else except
finally for from global if import lambda pass raise
return try while with yield
# Python 2 Keywords (otherwise Identifiers)
exec print
# Python 3 Keywords (otherwise Identifiers)
nonlocal
# Types
bool classmethod complex dict enumerate float frozenset int list object
property reversed set slice staticmethod str super tuple type
# Python 2 Types (otherwise Identifiers)
basestring buffer file long unicode xrange
# Python 3 Types (otherwise Identifiers)
bytearray bytes filter map memoryview open range zip
# Some Example code
import os
from package import ParentClass
@nonsenseDecorator
def doesNothing():
pass
class ExampleClass(ParentClass):
@staticmethod
def exa
View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment