4
<title>CodeMirror: CoffeeScript mode</title>
5
<link rel="stylesheet" href="../../lib/codemirror.css">
6
<script src="../../lib/codemirror.js"></script>
7
<script src="coffeescript.js"></script>
8
<style>.CodeMirror {border-top: 1px solid silver; border-bottom: 1px solid silver;}</style>
9
<link rel="stylesheet" href="../../doc/docs.css">
12
<h1>CodeMirror: CoffeeScript mode</h1>
13
<form><textarea id="code" name="code">
14
# CoffeeScript mode for CodeMirror
15
# Copyright (c) 2011 Jeff Pickhardt, released under
18
# Modified from the Python CodeMirror mode, which also is
19
# under the MIT License Copyright (c) 2010 Timothy Farrell.
21
# The following script, Underscore.coffee, is used to
22
# demonstrate CoffeeScript mode for CodeMirror.
24
# To download CoffeeScript mode for CodeMirror, go to:
25
# https://github.com/pickhardt/coffeescript-codemirror-mode
28
# (c) 2011 Jeremy Ashkenas, DocumentCloud Inc.**
29
# Underscore is freely distributable under the terms of the
30
# [MIT license](http://en.wikipedia.org/wiki/MIT_License).
31
# Portions of Underscore are inspired by or borrowed from
32
# [Prototype.js](http://prototypejs.org/api), Oliver Steele's
33
# [Functional](http://osteele.com), and John Resig's
34
# [Micro-Templating](http://ejohn.org).
35
# For all details and documentation:
36
# http://documentcloud.github.com/underscore/
42
# Establish the root object, `window` in the browser, or `global` on the server.
46
# Save the previous value of the `_` variable.
47
previousUnderscore = root._
50
# Establish the object that gets thrown to break out of a loop iteration.
51
# `StopIteration` is SOP on Mozilla.
52
breaker = if typeof(StopIteration) is 'undefined' then '__break__' else StopIteration
55
# Helper function to escape **RegExp** contents, because JS doesn't have one.
56
escapeRegExp = (string) -> string.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1')
59
# Save bytes in the minified (but not gzipped) version:
60
ArrayProto = Array.prototype
61
ObjProto = Object.prototype
64
# Create quick reference variables for speed access to core prototypes.
65
slice = ArrayProto.slice
66
unshift = ArrayProto.unshift
67
toString = ObjProto.toString
68
hasOwnProperty = ObjProto.hasOwnProperty
69
propertyIsEnumerable = ObjProto.propertyIsEnumerable
72
# All **ECMA5** native implementations we hope to use are declared here.
73
nativeForEach = ArrayProto.forEach
74
nativeMap = ArrayProto.map
75
nativeReduce = ArrayProto.reduce
76
nativeReduceRight = ArrayProto.reduceRight
77
nativeFilter = ArrayProto.filter
78
nativeEvery = ArrayProto.every
79
nativeSome = ArrayProto.some
80
nativeIndexOf = ArrayProto.indexOf
81
nativeLastIndexOf = ArrayProto.lastIndexOf
82
nativeIsArray = Array.isArray
83
nativeKeys = Object.keys
86
# Create a safe reference to the Underscore object for use below.
87
_ = (obj) -> new wrapper(obj)
90
# Export the Underscore object for **CommonJS**.
91
if typeof(exports) != 'undefined' then exports._ = _
94
# Export Underscore to global scope.
102
# Collection Functions
103
# --------------------
105
# The cornerstone, an **each** implementation.
106
# Handles objects implementing **forEach**, arrays, and raw objects.
107
_.each = (obj, iterator, context) ->
109
if nativeForEach and obj.forEach is nativeForEach
110
obj.forEach iterator, context
111
else if _.isNumber obj.length
112
iterator.call context, obj[i], i, obj for i in [0...obj.length]
114
iterator.call context, val, key, obj for own key, val of obj
116
throw e if e isnt breaker
120
# Return the results of applying the iterator to each element. Use JavaScript
121
# 1.6's version of **map**, if possible.
122
_.map = (obj, iterator, context) ->
123
return obj.map(iterator, context) if nativeMap and obj.map is nativeMap
125
_.each obj, (value, index, list) ->
126
results.push iterator.call context, value, index, list
130
# **Reduce** builds up a single result from a list of values. Also known as
131
# **inject**, or **foldl**. Uses JavaScript 1.8's version of **reduce**, if possible.
132
_.reduce = (obj, iterator, memo, context) ->
133
if nativeReduce and obj.reduce is nativeReduce
134
iterator = _.bind iterator, context if context
135
return obj.reduce iterator, memo
136
_.each obj, (value, index, list) ->
137
memo = iterator.call context, memo, value, index, list
141
# The right-associative version of **reduce**, also known as **foldr**. Uses
142
# JavaScript 1.8's version of **reduceRight**, if available.
143
_.reduceRight = (obj, iterator, memo, context) ->
144
if nativeReduceRight and obj.reduceRight is nativeReduceRight
145
iterator = _.bind iterator, context if context
146
return obj.reduceRight iterator, memo
147
reversed = _.clone(_.toArray(obj)).reverse()
148
_.reduce reversed, iterator, memo, context
151
# Return the first value which passes a truth test.
152
_.detect = (obj, iterator, context) ->
154
_.each obj, (value, index, list) ->
155
if iterator.call context, value, index, list
161
# Return all the elements that pass a truth test. Use JavaScript 1.6's
162
# **filter**, if it exists.
163
_.filter = (obj, iterator, context) ->
164
return obj.filter iterator, context if nativeFilter and obj.filter is nativeFilter
166
_.each obj, (value, index, list) ->
167
results.push value if iterator.call context, value, index, list
171
# Return all the elements for which a truth test fails.
172
_.reject = (obj, iterator, context) ->
174
_.each obj, (value, index, list) ->
175
results.push value if not iterator.call context, value, index, list
179
# Determine whether all of the elements match a truth test. Delegate to
180
# JavaScript 1.6's **every**, if it is present.
181
_.every = (obj, iterator, context) ->
182
iterator ||= _.identity
183
return obj.every iterator, context if nativeEvery and obj.every is nativeEvery
185
_.each obj, (value, index, list) ->
186
_.breakLoop() unless (result = result and iterator.call(context, value, index, list))
190
# Determine if at least one element in the object matches a truth test. Use
191
# JavaScript 1.6's **some**, if it exists.
192
_.some = (obj, iterator, context) ->
193
iterator ||= _.identity
194
return obj.some iterator, context if nativeSome and obj.some is nativeSome
196
_.each obj, (value, index, list) ->
197
_.breakLoop() if (result = iterator.call(context, value, index, list))
201
# Determine if a given value is included in the array or object,
203
_.include = (obj, target) ->
204
return _.indexOf(obj, target) isnt -1 if nativeIndexOf and obj.indexOf is nativeIndexOf
205
return true for own key, val of obj when val is target
209
# Invoke a method with arguments on every item in a collection.
210
_.invoke = (obj, method) ->
211
args = _.rest arguments, 2
212
(if method then val[method] else val).apply(val, args) for val in obj
215
# Convenience version of a common use case of **map**: fetching a property.
216
_.pluck = (obj, key) ->
217
_.map(obj, (val) -> val[key])
220
# Return the maximum item or (item-based computation).
221
_.max = (obj, iterator, context) ->
222
return Math.max.apply(Math, obj) if not iterator and _.isArray(obj)
223
result = computed: -Infinity
224
_.each obj, (value, index, list) ->
225
computed = if iterator then iterator.call(context, value, index, list) else value
226
computed >= result.computed and (result = {value: value, computed: computed})
230
# Return the minimum element (or element-based computation).
231
_.min = (obj, iterator, context) ->
232
return Math.min.apply(Math, obj) if not iterator and _.isArray(obj)
233
result = computed: Infinity
234
_.each obj, (value, index, list) ->
235
computed = if iterator then iterator.call(context, value, index, list) else value
236
computed < result.computed and (result = {value: value, computed: computed})
240
# Sort the object's values by a criterion produced by an iterator.
241
_.sortBy = (obj, iterator, context) ->
242
_.pluck(((_.map obj, (value, index, list) ->
243
{value: value, criteria: iterator.call(context, value, index, list)}
244
).sort((left, right) ->
245
a = left.criteria; b = right.criteria
246
if a < b then -1 else if a > b then 1 else 0
250
# Use a comparator function to figure out at what index an object should
251
# be inserted so as to maintain order. Uses binary search.
252
_.sortedIndex = (array, obj, iterator) ->
253
iterator ||= _.identity
257
mid = (low + high) >> 1
258
if iterator(array[mid]) < iterator(obj) then low = mid + 1 else high = mid
262
# Convert anything iterable into a real, live array.
263
_.toArray = (iterable) ->
264
return [] if (!iterable)
265
return iterable.toArray() if (iterable.toArray)
266
return iterable if (_.isArray(iterable))
267
return slice.call(iterable) if (_.isArguments(iterable))
271
# Return the number of elements in an object.
272
_.size = (obj) -> _.toArray(obj).length
278
# Get the first element of an array. Passing `n` will return the first N
279
# values in the array. Aliased as **head**. The `guard` check allows it to work
281
_.first = (array, n, guard) ->
282
if n and not guard then slice.call(array, 0, n) else array[0]
285
# Returns everything but the first entry of the array. Aliased as **tail**.
286
# Especially useful on the arguments object. Passing an `index` will return
287
# the rest of the values in the array from that index onward. The `guard`
288
# check allows it to work with **map**.
289
_.rest = (array, index, guard) ->
290
slice.call(array, if _.isUndefined(index) or guard then 1 else index)
293
# Get the last element of an array.
294
_.last = (array) -> array[array.length - 1]
297
# Trim out all falsy values from an array.
298
_.compact = (array) -> item for item in array when item
301
# Return a completely flattened version of an array.
302
_.flatten = (array) ->
303
_.reduce array, (memo, value) ->
304
return memo.concat(_.flatten(value)) if _.isArray value
310
# Return a version of the array that does not contain the specified value(s).
311
_.without = (array) ->
312
values = _.rest arguments
313
val for val in _.toArray(array) when not _.include values, val
316
# Produce a duplicate-free version of the array. If the array has already
317
# been sorted, you have the option of using a faster algorithm.
318
_.uniq = (array, isSorted) ->
320
for el, i in _.toArray array
321
memo.push el if i is 0 || (if isSorted is true then _.last(memo) isnt el else not _.include(memo, el))
325
# Produce an array that contains every item shared between all the
327
_.intersect = (array) ->
328
rest = _.rest arguments
329
_.select _.uniq(array), (item) ->
330
_.all rest, (other) ->
331
_.indexOf(other, item) >= 0
334
# Zip together multiple lists into a single array -- elements that share
335
# an index go together.
337
length = _.max _.pluck arguments, 'length'
338
results = new Array length
339
for i in [0...length]
340
results[i] = _.pluck arguments, String i
344
# If the browser doesn't supply us with **indexOf** (I'm looking at you, MSIE),
345
# we need this function. Return the position of the first occurrence of an
346
# item in an array, or -1 if the item is not included in the array.
347
_.indexOf = (array, item) ->
348
return array.indexOf item if nativeIndexOf and array.indexOf is nativeIndexOf
349
i = 0; l = array.length
351
if array[i] is item then return i else i++
355
# Provide JavaScript 1.6's **lastIndexOf**, delegating to the native function,
357
_.lastIndexOf = (array, item) ->
358
return array.lastIndexOf(item) if nativeLastIndexOf and array.lastIndexOf is nativeLastIndexOf
361
if array[i] is item then return i else i--
365
# Generate an integer Array containing an arithmetic progression. A port of
366
# [the native Python **range** function](http://docs.python.org/library/functions.html#range).
367
_.range = (start, stop, step) ->
370
i = start = if solo then 0 else a[0]
371
stop = if solo then a[0] else a[1]
373
len = Math.ceil((stop - start) / step)
374
return [] if len <= 0
375
range = new Array len
378
return range if (if step > 0 then i - stop else stop - i) >= 0
387
# Create a function bound to a given object (assigning `this`, and arguments,
388
# optionally). Binding with arguments is also known as **curry**.
389
_.bind = (func, obj) ->
390
args = _.rest arguments, 2
391
-> func.apply obj or root, args.concat arguments
394
# Bind all of an object's methods to that object. Useful for ensuring that
395
# all callbacks defined on an object belong to it.
397
funcs = if arguments.length > 1 then _.rest(arguments) else _.functions(obj)
398
_.each funcs, (f) -> obj[f] = _.bind obj[f], obj
402
# Delays a function for the given number of milliseconds, and then calls
403
# it with the arguments supplied.
404
_.delay = (func, wait) ->
405
args = _.rest arguments, 2
406
setTimeout((-> func.apply(func, args)), wait)
409
# Memoize an expensive function by storing its results.
410
_.memoize = (func, hasher) ->
412
hasher or= _.identity
414
key = hasher.apply this, arguments
415
return memo[key] if key of memo
416
memo[key] = func.apply this, arguments
419
# Defers a function, scheduling it to run after the current call stack has
422
_.delay.apply _, [func, 1].concat _.rest arguments
425
# Returns the first function passed as an argument to the second,
426
# allowing you to adjust arguments, run code before and after, and
427
# conditionally execute the original function.
428
_.wrap = (func, wrapper) ->
429
-> wrapper.apply wrapper, [func].concat arguments
432
# Returns a function that is the composition of a list of functions, each
433
# consuming the return value of the function that follows.
438
for i in [funcs.length - 1..0] by -1
439
args = [funcs[i].apply(this, args)]
446
# Retrieve the names of an object's properties.
447
_.keys = nativeKeys or (obj) ->
448
return _.range 0, obj.length if _.isArray(obj)
449
key for key, val of obj
452
# Retrieve the values of an object's properties.
454
_.map obj, _.identity
457
# Return a sorted list of the function names available in Underscore.
458
_.functions = (obj) ->
459
_.filter(_.keys(obj), (key) -> _.isFunction(obj[key])).sort()
462
# Extend a given object with all of the properties in a source object.
464
for source in _.rest(arguments)
465
obj[key] = val for key, val of source
469
# Create a (shallow-cloned) duplicate of an object.
471
return obj.slice 0 if _.isArray obj
475
# Invokes interceptor with the obj, and then returns obj.
476
# The primary purpose of this method is to "tap into" a method chain,
477
# in order to perform operations on intermediate results within
479
_.tap = (obj, interceptor) ->
484
# Perform a deep comparison to check if two objects are equal.
485
_.isEqual = (a, b) ->
486
# Check object identity.
487
return true if a is b
489
atype = typeof(a); btype = typeof(b)
490
return false if atype isnt btype
491
# Basic equality test (watch out for coercions).
492
return true if `a == b`
493
# One is falsy and the other truthy.
494
return false if (!a and b) or (a and !b)
495
# One of them implements an `isEqual()`?
496
return a.isEqual(b) if a.isEqual
497
# Check dates' integer values.
498
return a.getTime() is b.getTime() if _.isDate(a) and _.isDate(b)
500
return false if _.isNaN(a) and _.isNaN(b)
501
# Compare regular expressions.
502
if _.isRegExp(a) and _.isRegExp(b)
503
return a.source is b.source and
504
a.global is b.global and
505
a.ignoreCase is b.ignoreCase and
506
a.multiline is b.multiline
507
# If a is not an object by this point, we can't handle it.
508
return false if atype isnt 'object'
509
# Check for different array lengths before comparing contents.
510
return false if a.length and (a.length isnt b.length)
511
# Nothing else worked, deep compare the contents.
512
aKeys = _.keys(a); bKeys = _.keys(b)
513
# Different object sizes?
514
return false if aKeys.length isnt bKeys.length
515
# Recursive comparison of contents.
516
return false for key, val of a when !(key of b) or !_.isEqual(val, b[key])
520
# Is a given array or object empty?
522
return obj.length is 0 if _.isArray(obj) or _.isString(obj)
523
return false for own key of obj
527
# Is a given value a DOM element?
528
_.isElement = (obj) -> obj and obj.nodeType is 1
531
# Is a given value an array?
532
_.isArray = nativeIsArray or (obj) -> !!(obj and obj.concat and obj.unshift and not obj.callee)
535
# Is a given variable an arguments object?
536
_.isArguments = (obj) -> obj and obj.callee
539
# Is the given value a function?
540
_.isFunction = (obj) -> !!(obj and obj.constructor and obj.call and obj.apply)
543
# Is the given value a string?
544
_.isString = (obj) -> !!(obj is '' or (obj and obj.charCodeAt and obj.substr))
547
# Is a given value a number?
548
_.isNumber = (obj) -> (obj is +obj) or toString.call(obj) is '[object Number]'
551
# Is a given value a boolean?
552
_.isBoolean = (obj) -> obj is true or obj is false
555
# Is a given value a Date?
556
_.isDate = (obj) -> !!(obj and obj.getTimezoneOffset and obj.setUTCFullYear)
559
# Is the given value a regular expression?
560
_.isRegExp = (obj) -> !!(obj and obj.exec and (obj.ignoreCase or obj.ignoreCase is false))
563
# Is the given value NaN -- this one is interesting. `NaN != NaN`, and
564
# `isNaN(undefined) == true`, so we make sure it's a number first.
565
_.isNaN = (obj) -> _.isNumber(obj) and window.isNaN(obj)
568
# Is a given value equal to null?
569
_.isNull = (obj) -> obj is null
572
# Is a given variable undefined?
573
_.isUndefined = (obj) -> typeof obj is 'undefined'
579
# Run Underscore.js in noConflict mode, returning the `_` variable to its
580
# previous owner. Returns a reference to the Underscore object.
582
root._ = previousUnderscore
586
# Keep the identity function around for default iterators.
587
_.identity = (value) -> value
590
# Run a function `n` times.
591
_.times = (n, iterator, context) ->
592
iterator.call context, i for i in [0...n]
595
# Break out of the middle of an iteration.
596
_.breakLoop = -> throw breaker
599
# Add your own custom functions to the Underscore object, ensuring that
600
# they're correctly added to the OOP wrapper as well.
602
for name in _.functions(obj)
603
addToWrapper name, _[name] = obj[name]
606
# Generate a unique integer id (unique within the entire client session).
607
# Useful for temporary DOM ids.
609
_.uniqueId = (prefix) ->
610
(prefix or '') + idCounter++
613
# By default, Underscore uses **ERB**-style template delimiters, change the
614
# following template settings to use alternative delimiters.
615
_.templateSettings = {
618
interpolate: /<%=(.+?)%>/g
622
# JavaScript templating a-la **ERB**, pilfered from John Resig's
623
# *Secrets of the JavaScript Ninja*, page 83.
624
# Single-quote fix from Rick Strahl.
625
# With alterations for arbitrary delimiters, and to preserve whitespace.
626
_.template = (str, data) ->
627
c = _.templateSettings
628
endMatch = new RegExp("'(?=[^"+c.end.substr(0, 1)+"]*"+escapeRegExp(c.end)+")","g")
629
fn = new Function 'obj',
630
'var p=[],print=function(){p.push.apply(p,arguments);};' +
631
'with(obj||{}){p.push(\'' +
632
str.replace(/\r/g, '\\r')
633
.replace(/\n/g, '\\n')
634
.replace(/\t/g, '\\t')
635
.replace(endMatch,"���")
636
.split("'").join("\\'")
637
.split("���").join("'")
638
.replace(c.interpolate, "',$1,'")
639
.split(c.start).join("');")
640
.split(c.end).join("p.push('") +
641
"');}return p.join('');"
642
if data then fn(data) else fn
649
_.foldl = _.inject = _.reduce
650
_.foldr = _.reduceRight
654
_.contains = _.include
657
_.methods = _.functions
660
# Setup the OOP Wrapper
661
# ---------------------
663
# If Underscore is called as a function, it returns a wrapped object that
664
# can be used OO-style. This wrapper holds altered versions of all the
665
# underscore functions. Wrapped objects may be chained.
671
# Helper function to continue chaining intermediate results.
672
result = (obj, chain) ->
673
if chain then _(obj).chain() else obj
676
# A method to easily add functions to the OOP wrapper.
677
addToWrapper = (name, func) ->
678
wrapper.prototype[name] = ->
679
args = _.toArray arguments
680
unshift.call args, this._wrapped
681
result func.apply(_, args), this._chain
684
# Add all ofthe Underscore functions to the wrapper object.
688
# Add all mutator Array functions to the wrapper.
689
_.each ['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], (name) ->
690
method = Array.prototype[name]
691
wrapper.prototype[name] = ->
692
method.apply(this._wrapped, arguments)
693
result(this._wrapped, this._chain)
696
# Add all accessor Array functions to the wrapper.
697
_.each ['concat', 'join', 'slice'], (name) ->
698
method = Array.prototype[name]
699
wrapper.prototype[name] = ->
700
result(method.apply(this._wrapped, arguments), this._chain)
703
# Start chaining a wrapped Underscore object.
709
# Extracts the result from a wrapped and chained object.
710
wrapper::value = -> this._wrapped
713
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
716
<p><strong>MIME types defined:</strong> <code>text/x-coffeescript</code>.</p>
718
<p>The CoffeeScript mode was written by Jeff Pickhardt (<a href="LICENSE">license</a>).</p>