2
0

index.html 22 KB

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