Subversion-Projekte lars-tiefland.ci

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
776 lars 1
<!doctype html>
2
<title>CodeMirror: CoffeeScript mode</title>
3
<meta charset="utf-8" />
4
<link rel=stylesheet href="../../doc/docs.css">
5
<link rel="stylesheet" href="../../lib/codemirror.css">
6
<script src="../../lib/codemirror.js"></script>
7
<script src="coffeescript.js"></script>
8
<style>
9
    .CodeMirror {
10
        border-top: 1px solid silver;
11
        border-bottom: 1px solid silver;
12
    }
13
</style>
14
<div id=nav>
15
    <a href="http://codemirror.net">
16
        <h1>CodeMirror</h1>
17
        <img id=logo src="../../doc/logo.png">
18
    </a>
19
    <ul>
20
        <li>
21
            <a href="../../index.html">Home</a>
22
            <li>
23
                <a href="../../doc/manual.html">Manual</a>
24
                <li>
25
                    <a href="https://github.com/codemirror/codemirror">Code</a>
26
    </ul>
27
    <ul>
28
        <li>
29
            <a href="../index.html">Language modes</a>
30
            <li>
31
                <a class=active href="#">CoffeeScript</a>
32
    </ul>
33
</div>
34
<article>
35
    <h2>CoffeeScript mode</h2>
36
    <form>
37
        <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
38
            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
39
            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),
40
            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
41
            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
42
            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
43
            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
44
            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
45
            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
46
            = 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)
47
            # 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
48
            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
49
            _.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
50
            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
51
            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,
52
            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
53
            # 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
54
            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,
55
            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
56
            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,
57
            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
58
            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
59
            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**,
60
            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,
61
            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
62
            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 #
63
            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,
64
            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,
65
            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,
66
            (value, index, list) -> computed = if iterator then iterator.call(context, value, index, list) else value computed
67
            < result.computed and (result={ value: value, computed: computed}) result.value # Sort the object 's values by a criterion produced by an iterator.
68
_.sortBy = (obj, iterator, context) ->
69
  _.pluck(((_.map obj, (value, index, list) ->
70
    {value: value, criteria: iterator.call(context, value, index, list)}
71
  ).sort((left, right) ->
72
    a = left.criteria; b = right.criteria
73
    if a < b then -1 else if a > b then 1 else 0
74
  )), 'value ')
75
 
76
 
77
# Use a comparator function to figure out at what index an object should
78
# be inserted so as to maintain order. Uses binary search.
79
_.sortedIndex = (array, obj, iterator) ->
80
  iterator ||= _.identity
81
  low = 0
82
  high = array.length
83
  while low < high
84
    mid = (low + high) >> 1
85
    if iterator(array[mid]) < iterator(obj) then low = mid + 1 else high = mid
86
  low
87
 
88
 
89
# Convert anything iterable into a real, live array.
90
_.toArray = (iterable) ->
91
  return [] if (!iterable)
92
  return iterable.toArray() if (iterable.toArray)
93
  return iterable if (_.isArray(iterable))
94
  return slice.call(iterable) if (_.isArguments(iterable))
95
  _.values(iterable)
96
 
97
 
98
# Return the number of elements in an object.
99
_.size = (obj) -> _.toArray(obj).length
100
 
101
 
102
# Array Functions
103
# ---------------
104
 
105
# Get the first element of an array. Passing `n` will return the first N
106
# values in the array. Aliased as **head**. The `guard` check allows it to work
107
# with **map**.
108
_.first = (array, n, guard) ->
109
  if n and not guard then slice.call(array, 0, n) else array[0]
110
 
111
 
112
# Returns everything but the first entry of the array. Aliased as **tail**.
113
# Especially useful on the arguments object. Passing an `index` will return
114
# the rest of the values in the array from that index onward. The `guard`
115
# check allows it to work with **map**.
116
_.rest = (array, index, guard) ->
117
  slice.call(array, if _.isUndefined(index) or guard then 1 else index)
118
 
119
 
120
# Get the last element of an array.
121
_.last = (array) -> array[array.length - 1]
122
 
123
 
124
# Trim out all falsy values from an array.
125
_.compact = (array) -> item for item in array when item
126
 
127
 
128
# Return a completely flattened version of an array.
129
_.flatten = (array) ->
130
  _.reduce array, (memo, value) ->
131
    return memo.concat(_.flatten(value)) if _.isArray value
132
    memo.push value
133
    memo
134
  , []
135
 
136
 
137
# Return a version of the array that does not contain the specified value(s).
138
_.without = (array) ->
139
  values = _.rest arguments
140
  val for val in _.toArray(array) when not _.include values, val
141
 
142
 
143
# Produce a duplicate-free version of the array. If the array has already
144
# been sorted, you have the option of using a faster algorithm.
145
_.uniq = (array, isSorted) ->
146
  memo = []
147
  for el, i in _.toArray array
148
    memo.push el if i is 0 || (if isSorted is true then _.last(memo) isnt el else not _.include(memo, el))
149
  memo
150
 
151
 
152
# Produce an array that contains every item shared between all the
153
# passed-in arrays.
154
_.intersect = (array) ->
155
  rest = _.rest arguments
156
  _.select _.uniq(array), (item) ->
157
    _.all rest, (other) ->
158
      _.indexOf(other, item) >= 0
159
 
160
 
161
# Zip together multiple lists into a single array -- elements that share
162
# an index go together.
163
_.zip = ->
164
  length = _.max _.pluck arguments, 'length '
165
  results = new Array length
166
  for i in [0...length]
167
    results[i] = _.pluck arguments, String i
168
  results
169
 
170
 
171
# If the browser doesn't supply us with **indexOf** (I 'm looking at you, MSIE),
172
# we need this function. Return the position of the first occurrence of an
173
# item in an array, or -1 if the item is not included in the array.
174
_.indexOf = (array, item) ->
175
  return array.indexOf item if nativeIndexOf and array.indexOf is nativeIndexOf
176
  i = 0; l = array.length
177
  while l - i
178
    if array[i] is item then return i else i++
179
  -1
180
 
181
 
182
# 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
183
                of # [the native Python **range** function](http://docs.python.org/library/functions.html#range). _.range = (start, stop, step) -> a = arguments solo = a.length
184
                <=1 i=s tart=i f solo then 0 else a[0] stop=i f solo then a[0] else a[1] step=a
185
                    [2] or 1 len=M ath.ceil((stop - start) / step) return [] if len <=0 range=n ew 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
186
                    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
187
                    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
188
                    # 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
189
                    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
190
                    _, [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,
191
                    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 ->
192
                    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
193
                    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 =
194
                    (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
195
                    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
196
                    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) ->
197
                    # 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
198
                    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
199
                    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
200
                    # 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,
201
                    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,
202
                    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
203
                    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 #
204
                    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
205
                    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
206
                    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.
207
                    `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?
208
                    _.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
209
                    = -> 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]
210
                    # 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
211
                    _.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++ #
212
                    By default, Underscore uses **ERB**-style template delimiters, change the # following template settings to use alternative delimiters. _.templateSettings = { start: '
213
                    <%'
214
  end: '%>' interpolate: /
215
                        <%=(.+?)%>/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
216
                            = (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(\''
217
                            + 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('")
218
                            + "');}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
219
                            _.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
220
                            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()
221
                            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
222
                            # 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]
223
                            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]
224
                            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
225
                            object. wrapper::value = -> this._wrapped </textarea>
226
    </form>
227
    <script>
228
        var editor = CodeMirror.fromTextArea(document.getElementById("code"),
229
        {});
230
    </script>
231
    <p>
232
        <strong>MIME types defined:</strong> <code>text/x-coffeescript</code>.</p>
233
    <p>The CoffeeScript mode was written by Jeff Pickhardt.</p>
234
</article>