index.html 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  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>.CodeMirror {border-top: 1px solid silver; border-bottom: 1px solid silver;}</style>
  9. <div id=nav>
  10. <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a>
  11. <ul>
  12. <li><a href="../../index.html">Home</a>
  13. <li><a href="../../doc/manual.html">Manual</a>
  14. <li><a href="https://github.com/codemirror/codemirror">Code</a>
  15. </ul>
  16. <ul>
  17. <li><a href="../index.html">Language modes</a>
  18. <li><a class=active href="#">CoffeeScript</a>
  19. </ul>
  20. </div>
  21. <article>
  22. <h2>CoffeeScript mode</h2>
  23. <form><textarea id="code" name="code">
  24. # CoffeeScript mode for CodeMirror
  25. # Copyright (c) 2011 Jeff Pickhardt, released under
  26. # the MIT License.
  27. #
  28. # Modified from the Python CodeMirror mode, which also is
  29. # under the MIT License Copyright (c) 2010 Timothy Farrell.
  30. #
  31. # The following script, Underscore.coffee, is used to
  32. # demonstrate CoffeeScript mode for CodeMirror.
  33. #
  34. # To download CoffeeScript mode for CodeMirror, go to:
  35. # https://github.com/pickhardt/coffeescript-codemirror-mode
  36. # **Underscore.coffee
  37. # (c) 2011 Jeremy Ashkenas, DocumentCloud Inc.**
  38. # Underscore is freely distributable under the terms of the
  39. # [MIT license](http://en.wikipedia.org/wiki/MIT_License).
  40. # Portions of Underscore are inspired by or borrowed from
  41. # [Prototype.js](http://prototypejs.org/api), Oliver Steele's
  42. # [Functional](http://osteele.com), and John Resig's
  43. # [Micro-Templating](http://ejohn.org).
  44. # For all details and documentation:
  45. # http://documentcloud.github.com/underscore/
  46. # Baseline setup
  47. # --------------
  48. # Establish the root object, `window` in the browser, or `global` on the server.
  49. root = this
  50. # Save the previous value of the `_` variable.
  51. previousUnderscore = root._
  52. ### Multiline
  53. comment
  54. ###
  55. # Establish the object that gets thrown to break out of a loop iteration.
  56. # `StopIteration` is SOP on Mozilla.
  57. breaker = if typeof(StopIteration) is 'undefined' then '__break__' else StopIteration
  58. #### Docco style single line comment (title)
  59. # Helper function to escape **RegExp** contents, because JS doesn't have one.
  60. escapeRegExp = (string) -> string.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1')
  61. # Save bytes in the minified (but not gzipped) version:
  62. ArrayProto = Array.prototype
  63. 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
  70. # All **ECMA5** native implementations we hope to use are declared here.
  71. nativeForEach = ArrayProto.forEach
  72. nativeMap = ArrayProto.map
  73. nativeReduce = ArrayProto.reduce
  74. nativeReduceRight = ArrayProto.reduceRight
  75. nativeFilter = ArrayProto.filter
  76. nativeEvery = ArrayProto.every
  77. nativeSome = ArrayProto.some
  78. nativeIndexOf = ArrayProto.indexOf
  79. nativeLastIndexOf = ArrayProto.lastIndexOf
  80. nativeIsArray = Array.isArray
  81. nativeKeys = Object.keys
  82. # Create a safe reference to the Underscore object for use below.
  83. _ = (obj) -> new wrapper(obj)
  84. # Export the Underscore object for **CommonJS**.
  85. if typeof(exports) != 'undefined' then exports._ = _
  86. # Export Underscore to global scope.
  87. root._ = _
  88. # Current version.
  89. _.VERSION = '1.1.0'
  90. # Collection Functions
  91. # --------------------
  92. # The cornerstone, an **each** implementation.
  93. # Handles objects implementing **forEach**, arrays, and raw objects.
  94. _.each = (obj, iterator, context) ->
  95. try
  96. if nativeForEach and obj.forEach is nativeForEach
  97. obj.forEach iterator, context
  98. else if _.isNumber obj.length
  99. iterator.call context, obj[i], i, obj for i in [0...obj.length]
  100. else
  101. iterator.call context, val, key, obj for own key, val of obj
  102. catch e
  103. throw e if e isnt breaker
  104. obj
  105. # Return the results of applying the iterator to each element. Use JavaScript
  106. # 1.6's version of **map**, if possible.
  107. _.map = (obj, iterator, context) ->
  108. return obj.map(iterator, context) if nativeMap and obj.map is nativeMap
  109. results = []
  110. _.each obj, (value, index, list) ->
  111. results.push iterator.call context, value, index, list
  112. results
  113. # **Reduce** builds up a single result from a list of values. Also known as
  114. # **inject**, or **foldl**. Uses JavaScript 1.8's version of **reduce**, if possible.
  115. _.reduce = (obj, iterator, memo, context) ->
  116. if nativeReduce and obj.reduce is nativeReduce
  117. iterator = _.bind iterator, context if context
  118. return obj.reduce iterator, memo
  119. _.each obj, (value, index, list) ->
  120. memo = iterator.call context, memo, value, index, list
  121. memo
  122. # The right-associative version of **reduce**, also known as **foldr**. Uses
  123. # JavaScript 1.8's version of **reduceRight**, if available.
  124. _.reduceRight = (obj, iterator, memo, context) ->
  125. if nativeReduceRight and obj.reduceRight is nativeReduceRight
  126. iterator = _.bind iterator, context if context
  127. return obj.reduceRight iterator, memo
  128. reversed = _.clone(_.toArray(obj)).reverse()
  129. _.reduce reversed, iterator, memo, context
  130. # Return the first value which passes a truth test.
  131. _.detect = (obj, iterator, context) ->
  132. result = null
  133. _.each obj, (value, index, list) ->
  134. if iterator.call context, value, index, list
  135. result = value
  136. _.breakLoop()
  137. result
  138. # Return all the elements that pass a truth test. Use JavaScript 1.6's
  139. # **filter**, if it exists.
  140. _.filter = (obj, iterator, context) ->
  141. return obj.filter iterator, context if nativeFilter and obj.filter is nativeFilter
  142. results = []
  143. _.each obj, (value, index, list) ->
  144. results.push value if iterator.call context, value, index, list
  145. results
  146. # Return all the elements for which a truth test fails.
  147. _.reject = (obj, iterator, context) ->
  148. results = []
  149. _.each obj, (value, index, list) ->
  150. results.push value if not iterator.call context, value, index, list
  151. results
  152. # Determine whether all of the elements match a truth test. Delegate to
  153. # JavaScript 1.6's **every**, if it is present.
  154. _.every = (obj, iterator, context) ->
  155. iterator ||= _.identity
  156. return obj.every iterator, context if nativeEvery and obj.every is nativeEvery
  157. result = true
  158. _.each obj, (value, index, list) ->
  159. _.breakLoop() unless (result = result and iterator.call(context, value, index, list))
  160. result
  161. # Determine if at least one element in the object matches a truth test. Use
  162. # JavaScript 1.6's **some**, if it exists.
  163. _.some = (obj, iterator, context) ->
  164. iterator ||= _.identity
  165. return obj.some iterator, context if nativeSome and obj.some is nativeSome
  166. result = false
  167. _.each obj, (value, index, list) ->
  168. _.breakLoop() if (result = iterator.call(context, value, index, list))
  169. result
  170. # Determine if a given value is included in the array or object,
  171. # based on `===`.
  172. _.include = (obj, target) ->
  173. return _.indexOf(obj, target) isnt -1 if nativeIndexOf and obj.indexOf is nativeIndexOf
  174. return true for own key, val of obj when val is target
  175. false
  176. # Invoke a method with arguments on every item in a collection.
  177. _.invoke = (obj, method) ->
  178. args = _.rest arguments, 2
  179. (if method then val[method] else val).apply(val, args) for val in obj
  180. # Convenience version of a common use case of **map**: fetching a property.
  181. _.pluck = (obj, key) ->
  182. _.map(obj, (val) -> val[key])
  183. # Return the maximum item or (item-based computation).
  184. _.max = (obj, iterator, context) ->
  185. return Math.max.apply(Math, obj) if not iterator and _.isArray(obj)
  186. result = computed: -Infinity
  187. _.each obj, (value, index, list) ->
  188. computed = if iterator then iterator.call(context, value, index, list) else value
  189. computed >= result.computed and (result = {value: value, computed: computed})
  190. result.value
  191. # Return the minimum element (or element-based computation).
  192. _.min = (obj, iterator, context) ->
  193. return Math.min.apply(Math, obj) if not iterator and _.isArray(obj)
  194. result = computed: Infinity
  195. _.each obj, (value, index, list) ->
  196. computed = if iterator then iterator.call(context, value, index, list) else value
  197. computed < result.computed and (result = {value: value, computed: computed})
  198. result.value
  199. # Sort the object's values by a criterion produced by an iterator.
  200. _.sortBy = (obj, iterator, context) ->
  201. _.pluck(((_.map obj, (value, index, list) ->
  202. {value: value, criteria: iterator.call(context, value, index, list)}
  203. ).sort((left, right) ->
  204. a = left.criteria; b = right.criteria
  205. if a < b then -1 else if a > b then 1 else 0
  206. )), 'value')
  207. # Use a comparator function to figure out at what index an object should
  208. # be inserted so as to maintain order. Uses binary search.
  209. _.sortedIndex = (array, obj, iterator) ->
  210. iterator ||= _.identity
  211. low = 0
  212. high = array.length
  213. while low < high
  214. mid = (low + high) >> 1
  215. if iterator(array[mid]) < iterator(obj) then low = mid + 1 else high = mid
  216. low
  217. # Convert anything iterable into a real, live array.
  218. _.toArray = (iterable) ->
  219. return [] if (!iterable)
  220. return iterable.toArray() if (iterable.toArray)
  221. return iterable if (_.isArray(iterable))
  222. return slice.call(iterable) if (_.isArguments(iterable))
  223. _.values(iterable)
  224. # Return the number of elements in an object.
  225. _.size = (obj) -> _.toArray(obj).length
  226. # Array Functions
  227. # ---------------
  228. # Get the first element of an array. Passing `n` will return the first N
  229. # values in the array. Aliased as **head**. The `guard` check allows it to work
  230. # with **map**.
  231. _.first = (array, n, guard) ->
  232. if n and not guard then slice.call(array, 0, n) else array[0]
  233. # Returns everything but the first entry of the array. Aliased as **tail**.
  234. # Especially useful on the arguments object. Passing an `index` will return
  235. # the rest of the values in the array from that index onward. The `guard`
  236. # check allows it to work with **map**.
  237. _.rest = (array, index, guard) ->
  238. slice.call(array, if _.isUndefined(index) or guard then 1 else index)
  239. # Get the last element of an array.
  240. _.last = (array) -> array[array.length - 1]
  241. # Trim out all falsy values from an array.
  242. _.compact = (array) -> item for item in array when item
  243. # Return a completely flattened version of an array.
  244. _.flatten = (array) ->
  245. _.reduce array, (memo, value) ->
  246. return memo.concat(_.flatten(value)) if _.isArray value
  247. memo.push value
  248. memo
  249. , []
  250. # Return a version of the array that does not contain the specified value(s).
  251. _.without = (array) ->
  252. values = _.rest arguments
  253. val for val in _.toArray(array) when not _.include values, val
  254. # Produce a duplicate-free version of the array. If the array has already
  255. # been sorted, you have the option of using a faster algorithm.
  256. _.uniq = (array, isSorted) ->
  257. memo = []
  258. for el, i in _.toArray array
  259. memo.push el if i is 0 || (if isSorted is true then _.last(memo) isnt el else not _.include(memo, el))
  260. memo
  261. # Produce an array that contains every item shared between all the
  262. # passed-in arrays.
  263. _.intersect = (array) ->
  264. rest = _.rest arguments
  265. _.select _.uniq(array), (item) ->
  266. _.all rest, (other) ->
  267. _.indexOf(other, item) >= 0
  268. # Zip together multiple lists into a single array -- elements that share
  269. # an index go together.
  270. _.zip = ->
  271. length = _.max _.pluck arguments, 'length'
  272. results = new Array length
  273. for i in [0...length]
  274. results[i] = _.pluck arguments, String i
  275. results
  276. # If the browser doesn't supply us with **indexOf** (I'm looking at you, MSIE),
  277. # we need this function. Return the position of the first occurrence of an
  278. # item in an array, or -1 if the item is not included in the array.
  279. _.indexOf = (array, item) ->
  280. return array.indexOf item if nativeIndexOf and array.indexOf is nativeIndexOf
  281. i = 0; l = array.length
  282. while l - i
  283. if array[i] is item then return i else i++
  284. -1
  285. # Provide JavaScript 1.6's **lastIndexOf**, delegating to the native function,
  286. # if possible.
  287. _.lastIndexOf = (array, item) ->
  288. return array.lastIndexOf(item) if nativeLastIndexOf and array.lastIndexOf is nativeLastIndexOf
  289. i = array.length
  290. while i
  291. if array[i] is item then return i else i--
  292. -1
  293. # Generate an integer Array containing an arithmetic progression. A port of
  294. # [the native Python **range** function](http://docs.python.org/library/functions.html#range).
  295. _.range = (start, stop, step) ->
  296. a = arguments
  297. solo = a.length <= 1
  298. i = start = if solo then 0 else a[0]
  299. stop = if solo then a[0] else a[1]
  300. step = a[2] or 1
  301. len = Math.ceil((stop - start) / step)
  302. return [] if len <= 0
  303. range = new Array len
  304. idx = 0
  305. loop
  306. return range if (if step > 0 then i - stop else stop - i) >= 0
  307. range[idx] = i
  308. idx++
  309. i+= step
  310. # Function Functions
  311. # ------------------
  312. # Create a function bound to a given object (assigning `this`, and arguments,
  313. # optionally). Binding with arguments is also known as **curry**.
  314. _.bind = (func, obj) ->
  315. args = _.rest arguments, 2
  316. -> func.apply obj or root, args.concat arguments
  317. # Bind all of an object's methods to that object. Useful for ensuring that
  318. # all callbacks defined on an object belong to it.
  319. _.bindAll = (obj) ->
  320. funcs = if arguments.length > 1 then _.rest(arguments) else _.functions(obj)
  321. _.each funcs, (f) -> obj[f] = _.bind obj[f], obj
  322. obj
  323. # Delays a function for the given number of milliseconds, and then calls
  324. # it with the arguments supplied.
  325. _.delay = (func, wait) ->
  326. args = _.rest arguments, 2
  327. setTimeout((-> func.apply(func, args)), wait)
  328. # Memoize an expensive function by storing its results.
  329. _.memoize = (func, hasher) ->
  330. memo = {}
  331. hasher or= _.identity
  332. ->
  333. key = hasher.apply this, arguments
  334. return memo[key] if key of memo
  335. memo[key] = func.apply this, arguments
  336. # Defers a function, scheduling it to run after the current call stack has
  337. # cleared.
  338. _.defer = (func) ->
  339. _.delay.apply _, [func, 1].concat _.rest arguments
  340. # Returns the first function passed as an argument to the second,
  341. # allowing you to adjust arguments, run code before and after, and
  342. # conditionally execute the original function.
  343. _.wrap = (func, wrapper) ->
  344. -> wrapper.apply wrapper, [func].concat arguments
  345. # Returns a function that is the composition of a list of functions, each
  346. # consuming the return value of the function that follows.
  347. _.compose = ->
  348. funcs = arguments
  349. ->
  350. args = arguments
  351. for i in [funcs.length - 1..0] by -1
  352. args = [funcs[i].apply(this, args)]
  353. args[0]
  354. # Object Functions
  355. # ----------------
  356. # Retrieve the names of an object's properties.
  357. _.keys = nativeKeys or (obj) ->
  358. return _.range 0, obj.length if _.isArray(obj)
  359. key for key, val of obj
  360. # Retrieve the values of an object's properties.
  361. _.values = (obj) ->
  362. _.map obj, _.identity
  363. # Return a sorted list of the function names available in Underscore.
  364. _.functions = (obj) ->
  365. _.filter(_.keys(obj), (key) -> _.isFunction(obj[key])).sort()
  366. # Extend a given object with all of the properties in a source object.
  367. _.extend = (obj) ->
  368. for source in _.rest(arguments)
  369. obj[key] = val for key, val of source
  370. obj
  371. # Create a (shallow-cloned) duplicate of an object.
  372. _.clone = (obj) ->
  373. return obj.slice 0 if _.isArray obj
  374. _.extend {}, obj
  375. # Invokes interceptor with the obj, and then returns obj.
  376. # The primary purpose of this method is to "tap into" a method chain,
  377. # in order to perform operations on intermediate results within
  378. the chain.
  379. _.tap = (obj, interceptor) ->
  380. interceptor obj
  381. obj
  382. # Perform a deep comparison to check if two objects are equal.
  383. _.isEqual = (a, b) ->
  384. # Check object identity.
  385. return true if a is b
  386. # Different types?
  387. atype = typeof(a); btype = typeof(b)
  388. return false if atype isnt btype
  389. # Basic equality test (watch out for coercions).
  390. return true if `a == b`
  391. # One is falsy and the other truthy.
  392. return false if (!a and b) or (a and !b)
  393. # One of them implements an `isEqual()`?
  394. return a.isEqual(b) if a.isEqual
  395. # Check dates' integer values.
  396. return a.getTime() is b.getTime() if _.isDate(a) and _.isDate(b)
  397. # Both are NaN?
  398. return false if _.isNaN(a) and _.isNaN(b)
  399. # Compare regular expressions.
  400. if _.isRegExp(a) and _.isRegExp(b)
  401. return a.source is b.source and
  402. a.global is b.global and
  403. a.ignoreCase is b.ignoreCase and
  404. a.multiline is b.multiline
  405. # If a is not an object by this point, we can't handle it.
  406. return false if atype isnt 'object'
  407. # Check for different array lengths before comparing contents.
  408. return false if a.length and (a.length isnt b.length)
  409. # Nothing else worked, deep compare the contents.
  410. aKeys = _.keys(a); bKeys = _.keys(b)
  411. # Different object sizes?
  412. return false if aKeys.length isnt bKeys.length
  413. # Recursive comparison of contents.
  414. return false for key, val of a when !(key of b) or !_.isEqual(val, b[key])
  415. true
  416. # Is a given array or object empty?
  417. _.isEmpty = (obj) ->
  418. return obj.length is 0 if _.isArray(obj) or _.isString(obj)
  419. return false for own key of obj
  420. true
  421. # Is a given value a DOM element?
  422. _.isElement = (obj) -> obj and obj.nodeType is 1
  423. # Is a given value an array?
  424. _.isArray = nativeIsArray or (obj) -> !!(obj and obj.concat and obj.unshift and not obj.callee)
  425. # Is a given variable an arguments object?
  426. _.isArguments = (obj) -> obj and obj.callee
  427. # Is the given value a function?
  428. _.isFunction = (obj) -> !!(obj and obj.constructor and obj.call and obj.apply)
  429. # Is the given value a string?
  430. _.isString = (obj) -> !!(obj is '' or (obj and obj.charCodeAt and obj.substr))
  431. # Is a given value a number?
  432. _.isNumber = (obj) -> (obj is +obj) or toString.call(obj) is '[object Number]'
  433. # Is a given value a boolean?
  434. _.isBoolean = (obj) -> obj is true or obj is false
  435. # Is a given value a Date?
  436. _.isDate = (obj) -> !!(obj and obj.getTimezoneOffset and obj.setUTCFullYear)
  437. # Is the given value a regular expression?
  438. _.isRegExp = (obj) -> !!(obj and obj.exec and (obj.ignoreCase or obj.ignoreCase is false))
  439. # Is the given value NaN -- this one is interesting. `NaN != NaN`, and
  440. # `isNaN(undefined) == true`, so we make sure it's a number first.
  441. _.isNaN = (obj) -> _.isNumber(obj) and window.isNaN(obj)
  442. # Is a given value equal to null?
  443. _.isNull = (obj) -> obj is null
  444. # Is a given variable undefined?
  445. _.isUndefined = (obj) -> typeof obj is 'undefined'
  446. # Utility Functions
  447. # -----------------
  448. # Run Underscore.js in noConflict mode, returning the `_` variable to its
  449. # previous owner. Returns a reference to the Underscore object.
  450. _.noConflict = ->
  451. root._ = previousUnderscore
  452. this
  453. # Keep the identity function around for default iterators.
  454. _.identity = (value) -> value
  455. # Run a function `n` times.
  456. _.times = (n, iterator, context) ->
  457. iterator.call context, i for i in [0...n]
  458. # Break out of the middle of an iteration.
  459. _.breakLoop = -> throw breaker
  460. # Add your own custom functions to the Underscore object, ensuring that
  461. # they're correctly added to the OOP wrapper as well.
  462. _.mixin = (obj) ->
  463. for name in _.functions(obj)
  464. addToWrapper name, _[name] = obj[name]
  465. # Generate a unique integer id (unique within the entire client session).
  466. # Useful for temporary DOM ids.
  467. idCounter = 0
  468. _.uniqueId = (prefix) ->
  469. (prefix or '') + idCounter++
  470. # By default, Underscore uses **ERB**-style template delimiters, change the
  471. # following template settings to use alternative delimiters.
  472. _.templateSettings = {
  473. start: '<%'
  474. end: '%>'
  475. interpolate: /<%=(.+?)%>/g
  476. }
  477. # JavaScript templating a-la **ERB**, pilfered from John Resig's
  478. # *Secrets of the JavaScript Ninja*, page 83.
  479. # Single-quote fix from Rick Strahl.
  480. # With alterations for arbitrary delimiters, and to preserve whitespace.
  481. _.template = (str, data) ->
  482. c = _.templateSettings
  483. endMatch = new RegExp("'(?=[^"+c.end.substr(0, 1)+"]*"+escapeRegExp(c.end)+")","g")
  484. fn = new Function 'obj',
  485. 'var p=[],print=function(){p.push.apply(p,arguments);};' +
  486. 'with(obj||{}){p.push(\'' +
  487. str.replace(/\r/g, '\\r')
  488. .replace(/\n/g, '\\n')
  489. .replace(/\t/g, '\\t')
  490. .replace(endMatch,"���")
  491. .split("'").join("\\'")
  492. .split("���").join("'")
  493. .replace(c.interpolate, "',$1,'")
  494. .split(c.start).join("');")
  495. .split(c.end).join("p.push('") +
  496. "');}return p.join('');"
  497. if data then fn(data) else fn
  498. # Aliases
  499. # -------
  500. _.forEach = _.each
  501. _.foldl = _.inject = _.reduce
  502. _.foldr = _.reduceRight
  503. _.select = _.filter
  504. _.all = _.every
  505. _.any = _.some
  506. _.contains = _.include
  507. _.head = _.first
  508. _.tail = _.rest
  509. _.methods = _.functions
  510. # Setup the OOP Wrapper
  511. # ---------------------
  512. # If Underscore is called as a function, it returns a wrapped object that
  513. # can be used OO-style. This wrapper holds altered versions of all the
  514. # underscore functions. Wrapped objects may be chained.
  515. wrapper = (obj) ->
  516. this._wrapped = obj
  517. this
  518. # Helper function to continue chaining intermediate results.
  519. result = (obj, chain) ->
  520. if chain then _(obj).chain() else obj
  521. # A method to easily add functions to the OOP wrapper.
  522. addToWrapper = (name, func) ->
  523. wrapper.prototype[name] = ->
  524. args = _.toArray arguments
  525. unshift.call args, this._wrapped
  526. result func.apply(_, args), this._chain
  527. # Add all ofthe Underscore functions to the wrapper object.
  528. _.mixin _
  529. # Add all mutator Array functions to the wrapper.
  530. _.each ['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], (name) ->
  531. method = Array.prototype[name]
  532. wrapper.prototype[name] = ->
  533. method.apply(this._wrapped, arguments)
  534. result(this._wrapped, this._chain)
  535. # Add all accessor Array functions to the wrapper.
  536. _.each ['concat', 'join', 'slice'], (name) ->
  537. method = Array.prototype[name]
  538. wrapper.prototype[name] = ->
  539. result(method.apply(this._wrapped, arguments), this._chain)
  540. # Start chaining a wrapped Underscore object.
  541. wrapper::chain = ->
  542. this._chain = true
  543. this
  544. # Extracts the result from a wrapped and chained object.
  545. wrapper::value = -> this._wrapped
  546. </textarea></form>
  547. <script>
  548. var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
  549. </script>
  550. <p><strong>MIME types defined:</strong> <code>text/x-coffeescript</code>.</p>
  551. <p>The CoffeeScript mode was written by Jeff Pickhardt.</p>
  552. </article>