diff --git a/documentation/css/amy.css b/documentation/css/amy.css deleted file mode 100644 index 24c1e5b9..00000000 --- a/documentation/css/amy.css +++ /dev/null @@ -1,147 +0,0 @@ -pre.amy .PolymorphicVariants { - color: #60B0FF; - font-style: italic; -} -pre.amy .KeywordDecorator { - color: #D0D0FF; -} -pre.amy .Punctuation { - color: #805080; -} -pre.amy .InheritedClass { -} -pre.amy .InvalidDepricated { - background-color: #CC66FF; - color: #200020; -} -pre.amy .LibraryVariable { -} -pre.amy .TokenReferenceOcamlyacc { - color: #3CB0D0; -} -pre.amy .Storage { - color: #B0FFF0; -} -pre.amy .KeywordOperator { - color: #A0A0FF; -} -pre.amy .CharacterConstant { - color: #666666; -} -pre.amy .line-numbers { - background-color: #800000; - color: #000000; -} -pre.amy .ClassName { - color: #70E080; -} -pre.amy .Int64Constant { - font-style: italic; -} -pre.amy .NonTerminalReferenceOcamlyacc { - color: #C0F0F0; -} -pre.amy .TokenDefinitionOcamlyacc { - color: #3080A0; -} -pre.amy .ClassType { - color: #70E0A0; -} -pre.amy .ControlKeyword { - color: #80A0FF; -} -pre.amy .LineNumberDirectives { - text-decoration: underline; - color: #C080C0; -} -pre.amy .FloatingPointConstant { - text-decoration: underline; -} -pre.amy .Int32Constant { - font-weight: bold; -} -pre.amy .TagName { - color: #009090; -} -pre.amy .ModuleTypeDefinitions { - text-decoration: underline; - color: #B000B0; -} -pre.amy .Integer { - color: #7090B0; -} -pre.amy .Camlp4TempParser { -} -pre.amy .InvalidIllegal { - font-weight: bold; - background-color: #FFFF00; - color: #400080; -} -pre.amy .LibraryConstant { - background-color: #200020; -} -pre.amy .ModuleDefinitions { - color: #B000B0; -} -pre.amy .Variants { - color: #60B0FF; -} -pre.amy .CompilerDirectives { - color: #C080C0; -} -pre.amy .FloatingPointInfixOperator { - text-decoration: underline; -} -pre.amy .BuiltInConstant1 { -} -pre.amy { - background-color: #200020; - color: #D0D0FF; -} -pre.amy .FunctionArgument { - color: #80B0B0; -} -pre.amy .FloatingPointPrefixOperator { - text-decoration: underline; -} -pre.amy .NativeintConstant { - font-weight: bold; -} -pre.amy .BuiltInConstant { - color: #707090; -} -pre.amy .BooleanConstant { - color: #8080A0; -} -pre.amy .LibraryClassType { -} -pre.amy .TagAttribute { -} -pre.amy .Keyword { - color: #A080FF; -} -pre.amy .UserDefinedConstant { -} -pre.amy .String { - color: #999999; -} -pre.amy .Camlp4Code { - background-color: #350060; -} -pre.amy .NonTerminalDefinitionOcamlyacc { - color: #90E0E0; -} -pre.amy .FunctionName { - color: #50A0A0; -} -pre.amy .SupportModules { - color: #A00050; -} -pre.amy .Variable { - color: #008080; -} -pre.amy .Comment { - background-color: #200020; - color: #404080; - font-style: italic; -} diff --git a/documentation/css/docs.css b/documentation/css/docs.css index f7b4f72c..5e8b3c4c 100644 --- a/documentation/css/docs.css +++ b/documentation/css/docs.css @@ -1,23 +1,20 @@ body { font-size: 14px; line-height: 20px; - background: #f3f3f9; color: #191933; font-family: Arial, Helvetica, sans-serif; } div.container { width: 950px; - margin: 50px 0 50px 50px; + margin: 100px 0 50px 50px; } p { - padding-left: 13px; width: 625px; } a { color: #000055; } h1, h2, h3, h4, h5, h6 { - padding-left: 13px; margin-top: 40px; } br.clear { @@ -86,6 +83,86 @@ div.code { border-left: 0; } +#fadeout { + z-index: 50; + position: fixed; + left: 0; top: 0; right: 0; + height: 50px; + background: -webkit-gradient(linear, left top, left bottom, from(rgba(255, 255, 255, 255)), to(rgba(255, 255, 255, 0))); + background: -moz-linear-gradient(top, rgba(255, 255, 255, 255), rgba(255, 255, 255, 0)); +} + +#flybar { + position: fixed; + z-index: 100; + height: 50px; + left: 25px; right: 25px; top: 25px; + background: #ddd; + background: -webkit-gradient(linear, left top, left bottom, from(#f5f5f5), to(#d0d0d0)); + background: -moz-linear-gradient(top, #f5f5f5, #d0d0d0); + filter: progid:DXImageTransform.Microsoft.Gradient(GradientType=0, StartColorStr='#F5F5F5', EndColorStr='#D0D0D0'); + -webkit-border-radius: 20px; -moz-border-radius: 20px; border-radius: 20px; + -webkit-box-shadow: 0 0 25px #777; -moz-box-shadow: 0 0 25px #777; +} + #logo { + width: 215px; height: 50px; + background: url('logo.png'); + position: absolute; + top: 0px; left: 5px; + } + .navigation { + height: 50px; + font: bold 11px/50px Arial; + text-transform: uppercase; + position: absolute; + left: 250px; + padding: 0 10px; + border: 1px solid #bbb; + border-top: 0; border-bottom: 0; + cursor: pointer; + color: #595977; + } + .navigation:hover { + background: #d0d0d0; + background: -webkit-gradient(linear, left top, left bottom, from(#f0f0f0), to(#c0c0c0)); + background: -moz-linear-gradient(top, #f0f0f0, #c0c0c0); + filter: progid:DXImageTransform.Microsoft.Gradient(GradientType=0, StartColorStr='#F0F0F0', EndColorStr='#C0C0C0'); + } + .navigation .contents { + display: none; + position: absolute; + background: #fff; + top: 50px; left: 0; + padding: 5px 0; + -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; + -webkit-border-top-left-radius: 0; -moz-border-radius-topleft: 0; + -webkit-border-top-right-radius: 0; -moz-border-radius-topright: 0; + -webkit-box-shadow: 0 0 25px #777; -moz-box-shadow: 0 0 25px #777; + } + .navigation:hover .contents { + display: block; + } + .navigation .contents a { + display: block; + width: 300px; + text-transform: none; + text-decoration: none; + font-weight: normal; + height: 12px; + line-height: 12px; + padding: 4px 10px; + } + .navigation .contents a:hover { + background: #f0f0f0; + } + +.bookmark { + display: block; + width: 0; height: 0; + position: relative; + top: -90px; +} + #repl_source { border: 0; padding: 5px 7px; diff --git a/documentation/css/logo.png b/documentation/css/logo.png new file mode 100644 index 00000000..2b1e40a4 Binary files /dev/null and b/documentation/css/logo.png differ diff --git a/documentation/css/old_docs.css b/documentation/css/old_docs.css new file mode 100644 index 00000000..f7b4f72c --- /dev/null +++ b/documentation/css/old_docs.css @@ -0,0 +1,98 @@ +body { + font-size: 14px; + line-height: 20px; + background: #f3f3f9; + color: #191933; + font-family: Arial, Helvetica, sans-serif; +} +div.container { + width: 950px; + margin: 50px 0 50px 50px; +} +p { + padding-left: 13px; + width: 625px; +} +a { + color: #000055; +} +h1, h2, h3, h4, h5, h6 { + padding-left: 13px; + margin-top: 40px; +} +br.clear { + height: 0; + clear: both; +} +b.header { + color: #000055; + display: block; + margin: 40px 0 5px 0; + font-size: 16px; +} +li { + margin-bottom: 7px; +} +table { + margin: 16px 0 0 13px; padding: 0; + width: 625px; +} + tr, td { + margin: 0; padding: 0; + } + td { + padding: 9px 15px 9px 0; + } +code, pre, tt, textarea { + font-family: Monaco, Consolas, "Lucida Console", monospace; + font-size: 12px; + line-height: 18px; + color: #191955; + white-space: pre-wrap; + word-wrap: break-word; +} + tt { + background: #f8f8ff; + border: 1px solid #dedede; + font-size: 85%; + padding: 0px 0.2em; + } + pre { + border-left: 6px solid #222255; + margin-left: 13px; + padding: 3px 0 3px 12px; + font-size: 12px; + } +div.code { + position: relative; + border: 1px solid #cacaca; + background: #fff; + padding: 7px 0 10px 0; + -moz-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px; + -webkit-box-shadow: 0px 0px 7px #cacaca; +} + div.code button { + position: absolute; + right: 8px; bottom: 8px; + } + div.code pre, div.code textarea { + float: left; + width: 450px; + border-left: 1px dotted #559; + padding: 0 0 0 12px; + margin: 0; + } + div.code pre:first-child { + border-left: 0; + } + +#repl_source { + border: 0; + padding: 5px 7px; + margin-left: 5px; + min-height: 250px; + resize: none; +} +#repl_results { + min-height: 260px; +} \ No newline at end of file diff --git a/documentation/index.html.erb b/documentation/index.html.erb index 915a08d9..b5fe3d39 100644 --- a/documentation/index.html.erb +++ b/documentation/index.html.erb @@ -24,11 +24,49 @@ + +
+ +
+ + +
-

CoffeeScript

-

CoffeeScript is a little language that compiles into JavaScript. Think of it as JavaScript's less ostentatious kid brother — the same genes, @@ -54,39 +92,10 @@ 0.3.2

-

Table of Contents

- -

- Mini Overview
- Installation and Usage
- Try CoffeeScript
- Significant Whitespace
- Functions and Invocation
- Assignment
- Objects and Arrays
- Lexical Scoping and Variable Safety
- Conditionals, Ternaries, and Conditional Assignment
- Aliases
- Splats...
- Arguments are Arrays
- While Loops
- Comprehensions (Arrays, Objects, and Ranges)
- Array Slicing and Splicing with Ranges
- Everything is an Expression
- The Existential Operator
- Inheritance, and Calling Super from a Subclass
- Pattern Matching
- Function Binding
- Embedded JavaScript
- Switch/When/Else
- Try/Catch/Finally
- Chained Comparisons
- Multiline Strings and Heredocs
- Resources
- Change Log
-

- -

Mini Overview

+

+ + Mini Overview +

CoffeeScript on the left, compiled JavaScript output on the right.

@@ -105,7 +114,10 @@ examples folder.

-

Installation and Usage

+

+ + Installation and Usage +

The CoffeeScript compiler is written in pure Ruby, and is available @@ -225,7 +237,10 @@ coffee --interactive coffee --watch --lint experimental.coffee coffee --print app/scripts/*.coffee > concatenation.js -

Try CoffeeScript

+

+ + Try CoffeeScript +

Here's a live version of the CoffeeScript compiler, running within @@ -256,7 +271,8 @@ print reverse 'tpircseeffoc'

-

+

+ Significant Whitespace CoffeeScript uses Python-style significant whitespace: You don't need to use semicolons ; to terminate expressions, ending @@ -278,7 +294,8 @@ print reverse 'tpircseeffoc' as long as CoffeeScript can determine that the line hasn't finished yet.

-

+

+ Functions and Invocation Functions are defined by a list of parameters, an arrow, and the function body. The empty function looks like this: ->. All @@ -290,7 +307,8 @@ print reverse 'tpircseeffoc' ((x) -> x * x)

-

+

+ Assignment Use a colon : to assign, as in JSON. Equal signs are only needed for @@ -303,7 +321,8 @@ print reverse 'tpircseeffoc' lexical scope, so that assignment may always be performed within expressions.

-

+

+ Objects and Arrays Object and Array literals look very similar to their JavaScript cousins. When you spread out each assignment on a separate line, the commas are @@ -313,7 +332,8 @@ print reverse 'tpircseeffoc'

<%= code_for('objects_and_arrays', 'song.join(",")') %> -

+

+ Lexical Scoping and Variable Safety The CoffeeScript compiler takes care to make sure that all of your variables are properly declared within lexical scope — you never need to write @@ -343,7 +363,8 @@ print reverse 'tpircseeffoc' CommonJS and the browser: root: exports ? this

-

+

+ Conditionals, Ternaries, and Conditional Assignment If/else statements can be written without the use of parentheses and curly brackets. As with functions and other block expressions, @@ -362,7 +383,8 @@ print reverse 'tpircseeffoc' truthy variables.

-

+

+ Aliases Because the == operator frequently causes undesirable coercion, is intransitive, and has a different meaning than in other languages, @@ -395,7 +417,8 @@ print reverse 'tpircseeffoc'

<%= code_for('aliases') %> -

+

+ Splats... The JavaScript arguments object is a useful way to work with functions that accept variable numbers of arguments. CoffeeScript provides @@ -404,7 +427,8 @@ print reverse 'tpircseeffoc'

<%= code_for('splats', true) %> -

+

+ Arguments are Arrays If you reference the arguments object directly, it will be converted into a real Array, making all of the @@ -413,7 +437,8 @@ print reverse 'tpircseeffoc'

<%= code_for('arguments', true) %> -

+

+ While Loops The only low-level loop that CoffeeScript provides is the while loop. The main difference from JavaScript is that the while loop can be used @@ -428,7 +453,8 @@ print reverse 'tpircseeffoc' each (forEach) style iterators, or...

-

+

+ Comprehensions (Arrays, Objects, and Ranges) For your looping needs, CoffeeScript provides array comprehensions similar to Python's. They replace (and compile into) for loops, with @@ -452,7 +478,8 @@ print reverse 'tpircseeffoc'

<%= code_for('object_comprehensions', 'ages.join(", ")') %> -

+

+ Array Slicing and Splicing with Ranges CoffeeScript borrows Ruby's range syntax @@ -468,7 +495,8 @@ print reverse 'tpircseeffoc'

<%= code_for('splices', 'numbers') %> -

+

+ Everything is an Expression (at least, as much as possible) You might have noticed how even though we don't add return statements to CoffeeScript functions, they nonetheless return their final value. @@ -507,7 +535,8 @@ print reverse 'tpircseeffoc' CoffeeScript won't try to perform the conversion.

-

+

+ The Existential Operator It's a little difficult to check for the existence of a variable in JavaScript. if (variable) ... comes close, but fails for zero, @@ -536,7 +565,8 @@ print reverse 'tpircseeffoc' in Groovy.

-

+

+ Inheritance, and Calling Super from a Subclass JavaScript's prototypal inheritance has always been a bit of a brain-bender, with a whole family tree of libraries that provide a cleaner @@ -558,7 +588,8 @@ print reverse 'tpircseeffoc'

<%= code_for('super', true) %> -

+

+ Pattern Matching (Destructuring Assignment) To make extracting values from complex arrays and objects more convenient, CoffeeScript implements ECMAScript Harmony's proposed @@ -580,7 +611,8 @@ print reverse 'tpircseeffoc'

<%= code_for('object_extraction', 'poet + " — " + street') %> -

+

+ Function binding The fat arrow => can be used to both define a function, and to bind it to the current value of this, right on the spot. This is helpful @@ -591,7 +623,8 @@ print reverse 'tpircseeffoc'

<%= code_for('fat_arrow') %> -

+

+ Embedded JavaScript Hopefully, you'll never need to use it, but if you ever need to intersperse snippets of JavaScript within your CoffeeScript, you can @@ -599,7 +632,8 @@ print reverse 'tpircseeffoc'

<%= code_for('embedded', 'hi()') %> -

+

+ Switch/When/Else Switch statements in JavaScript are rather broken. You can only do comparisons based on string equality, and need to remember to break at the end of @@ -616,14 +650,16 @@ print reverse 'tpircseeffoc'

<%= code_for('switch') %> -

+

+ Try/Catch/Finally Try/catch statements are just about the same as JavaScript (although they work as expressions).

<%= code_for('try') %> -

+

+ Chained Comparisons CoffeeScript borrows chained comparisons @@ -632,7 +668,8 @@ print reverse 'tpircseeffoc'

<%= code_for('comparisons', 'healthy') %> -

+

+ Multiline Strings and Heredocs Multiline strings are allowed in CoffeeScript.

@@ -645,7 +682,10 @@ print reverse 'tpircseeffoc'

<%= code_for('heredocs') %> -

Resources

+

+ + Resources +

-

Change Log

+

+ + Change Log +

0.3.2 diff --git a/documentation/old_index.html.erb b/documentation/old_index.html.erb new file mode 100644 index 00000000..915a08d9 --- /dev/null +++ b/documentation/old_index.html.erb @@ -0,0 +1,866 @@ +<% + require 'uv' + def code_for(file, executable=false) + @stripper ||= /(\A\(function\(\)\{\n|\}\)\(\);\Z|^ )/ + return '' unless File.exists?("documentation/js/#{file}.js") + cs = File.read("documentation/coffee/#{file}.coffee") + js = File.read("documentation/js/#{file}.js").gsub(@stripper, '') + cshtml = Uv.parse(cs, 'xhtml', 'coffeescript', false, 'idle', false) + jshtml = Uv.parse(js, 'xhtml', 'javascript', false, 'idle', false) + append = executable == true ? '' : "alert(#{executable});" + run = executable == true ? 'run' : "run: #{executable}" + button = executable ? "" : '' + "

#{cshtml}#{jshtml}#{button}
" + end +%> + + + + + + + CoffeeScript + + + + + +
+ +

CoffeeScript

+ +

+ CoffeeScript is a little language that compiles into JavaScript. Think + of it as JavaScript's less ostentatious kid brother — the same genes, + roughly the same height, but a different sense of style. Apart from a handful of + bonus goodies, statements in CoffeeScript correspond one-to-one with their + equivalent in JavaScript, it's just another way of saying it. +

+ +

+ Disclaimer: + CoffeeScript is just for fun and seriously alpha. I'm sure that there are still + plenty of holes in the walls and leaks in the roof. There are no guarantees + that the syntax won't change between versions. That said, + it compiles into clean JavaScript (the good parts) that can use existing + JavaScript libraries seamlessly, and passes through + JSLint without warnings. The compiled + output is quite readable — pretty-printed, with comments + preserved intact. +

+ +

+ Latest Version: + 0.3.2 +

+ +

Table of Contents

+ +

+ Mini Overview
+ Installation and Usage
+ Try CoffeeScript
+ Significant Whitespace
+ Functions and Invocation
+ Assignment
+ Objects and Arrays
+ Lexical Scoping and Variable Safety
+ Conditionals, Ternaries, and Conditional Assignment
+ Aliases
+ Splats...
+ Arguments are Arrays
+ While Loops
+ Comprehensions (Arrays, Objects, and Ranges)
+ Array Slicing and Splicing with Ranges
+ Everything is an Expression
+ The Existential Operator
+ Inheritance, and Calling Super from a Subclass
+ Pattern Matching
+ Function Binding
+ Embedded JavaScript
+ Switch/When/Else
+ Try/Catch/Finally
+ Chained Comparisons
+ Multiline Strings and Heredocs
+ Resources
+ Change Log
+

+ +

Mini Overview

+ +

CoffeeScript on the left, compiled JavaScript output on the right.

+ + <%= code_for('overview', 'cubed_list') %> + +

+ For a longer CoffeeScript example, check out + Underscore.coffee, a port + of the Underscore.js + library of helper functions. Underscore.coffee can pass the entire Underscore.js + test suite. The CoffeeScript version is faster than the original for a number + of methods (in general, due to the speed of CoffeeScript's array comprehensions), and + after being minified and gzipped, is only 241 bytes larger than the original + JavaScript version. + Additional examples are included in the source repository, inside the + examples folder. +

+ +

Installation and Usage

+ +

+ The CoffeeScript compiler is written in pure Ruby, and is available + as a Ruby Gem. +

+ +
+gem install coffee-script
+ +

+ Installing the gem provides the coffee command, which can + be used to compile CoffeeScript .coffee files into JavaScript, as + well as debug them. In conjunction with + Node.js (or Narwhal), the coffee + command also provides direct evaluation and an interactive REPL. + When compiling to JavaScript, coffee writes the output + as .js files in the same directory by default, but output + can be customized with the following options: +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
-i, --interactive + Launch an interactive CoffeeScript session. + Requires Node.js, + or Narwhal, with --narwhal. +
-r, --run + Compile and execute scripts without saving the intermediate + JavaScript. Requires Node.js, + or Narwhal, with --narwhal. +
-o, --output [DIR] + Write out all compiled JavaScript files into the specified directory. +
-w, --watch + Watch the modification times of the coffee-scripts, recompiling as + soon as a change occurs. +
-p, --print + Instead of writing out the JavaScript as a file, print it + directly to stdout. +
-l, --lint + If the jsl (JavaScript Lint) command is installed, use it + to check the compilation of a CoffeeScript file. (Handy in + conjunction with --watch) +
-e, --eval + Compile and print a little snippet of CoffeeScript directly from the + command line (or from stdin). For example:
coffee -e "square: (x) -> x * x" +
-t, --tokens + Instead of parsing the CoffeeScript, just lex it, and print out the + token stream: [:IDENTIFIER, "square"], [":", ":"], [:PARAM, "x"] ... +
-v, --verbose + As the JavaScript is being generated, print out every step of code + generation, including lexical scope and the nodes in the + AST. +
-n, --no-wrap + Compile the JavaScript without the top-level function safety wrapper. + (Used for CoffeeScript as a Node.js module.) +
-g, --globals + Suppress all variable declarations at the top-level, effectively adding + those variables to the global scope. (Used by the REPL.) +
--install-bundle + Install the TextMate bundle for CoffeeScript syntax highlighting. +
+ +

+ Examples: +

+ +
+coffee path/to/script.coffee
+coffee --interactive
+coffee --watch --lint experimental.coffee
+coffee --print app/scripts/*.coffee > concatenation.js
+ +

Try CoffeeScript

+ +

+ Here's a live version of the CoffeeScript compiler, running within + your browser.
Hit the compile button to generate JavaScript + on the right-hand side. + You can also paste in any of the examples from below. +

+ +
+ +

+      
+      
+
+ +

Language Reference

+ +

+ + This reference is structured so that it can be read from top to bottom, + if you like. Later sections use ideas and syntax previously introduced. + Familiarity with JavaScript is assumed. + In all of the following examples, the source CoffeeScript is provided on + the left, and the direct compilation into JavaScript is on the right. + +

+ +

+ Significant Whitespace + CoffeeScript uses Python-style significant whitespace: You don't need to + use semicolons ; to terminate expressions, ending + the line will do just as well. Semicolons can still be used to fit + multiple expressions onto a single line. Instead of using curly braces + { } to delimit blocks of code (like functions, + if-statements, + switch, and try/catch), + use indentation. +

+ +

+ You don't need to use parentheses to invoke a function, if you're passing + arguments:
print "coffee" +

+ +

+ You can use newlines to break up your expression into smaller pieces, + as long as CoffeeScript can determine that the line hasn't finished yet. +

+ +

+ Functions and Invocation + Functions are defined by a list of parameters, an arrow, and the + function body. The empty function looks like this: ->. All + functions in CoffeeScript are named by default, for easier debugging. +

+ <%= code_for('functions', 'cube(5)') %> +

+ If you'd like to create an anonymous function, just wrap it in parentheses: + ((x) -> x * x) +

+ +

+ Assignment + Use a colon : to assign, as in + JSON. Equal signs are only needed for + mathy things. While colons are preferred, the two may be used interchangeably, + even within object literals. +

+ <%= code_for('assignment', 'greeting') %> +

+ Declaration of new variables are pushed up to the top of the nearest + lexical scope, so that assignment may always be performed within expressions. +

+ +

+ Objects and Arrays + Object and Array literals look very similar to their JavaScript cousins. + When you spread out each assignment on a separate line, the commas are + optional. In this way, assigning object properties looks the same as + assigning local variables, and can be moved around freely. Feel free to mix + and match the two styles. +

+ <%= code_for('objects_and_arrays', 'song.join(",")') %> + +

+ Lexical Scoping and Variable Safety + The CoffeeScript compiler takes care to make sure that all of your variables + are properly declared within lexical scope — you never need to write + var yourself. +

+ <%= code_for('scope', 'new_num') %> +

+ Notice how the all of the variable declarations have been pushed up to + the top of the closest scope, the first time they appear. + num is not redeclared within the inner function, because it's + already in scope; the new_num within the function, on the other hand, + should not be able to change the value of the external variable of the same name, and + therefore has a declaration of its own. +

+

+ Although suppressed within this documentation for clarity, all + CoffeeScript output is wrapped in an anonymous function: + (function(){ ... })(); This safety wrapper, combined with the + automatic generation of the var keyword, make it exceedingly difficult + to pollute the global namespace by accident. +

+

+ If you'd like to create top-level variables for other scripts to use, + attach them as properties on window, or on the exports + object in CommonJS. The existential operator (below), gives you a + reliable way to figure out where to add them, if you're targeting both + CommonJS and the browser: root: exports ? this +

+ +

+ Conditionals, Ternaries, and Conditional Assignment + If/else statements can be written without the use of parentheses and + curly brackets. As with functions and other block expressions, + multi-line conditionals are delimited by indentation. There's also a handy + postfix form, with the if or unless at the end. +

+

+ CoffeeScript will compile if statements using the ternary operator + when possible, to make it easier to use the result as an expression. +

+ <%= code_for('conditionals') %> +

+ The conditional assignment operators are included: ||=, + which only assigns a value to a variable if the variable's current value + is falsy, and &&=, which only replaces the value of + truthy variables. +

+ +

+ Aliases + Because the == operator frequently causes undesirable coercion, + is intransitive, and has a different meaning than in other languages, + CoffeeScript compiles == into ===, and != into + !==. + In addition, is compiles into ===, + and isnt into !==. +

+

+ You can use not as an alias for !. +

+

+ For logic, and compiles to &&, and or + into ||. +

+

+ Instead of a newline or semicolon, then can be used to separate + conditions from expressions, in while, + if/else, and switch/when statements. +

+

+ As in YAML, on and yes + are the same as boolean true, while off and no are boolean false. +

+

+ For single-line statements, unless can be used as the inverse of if. +

+

+ As a shortcut for this.property, you can use @property. +

+ <%= code_for('aliases') %> + +

+ Splats... + The JavaScript arguments object is a useful way to work with + functions that accept variable numbers of arguments. CoffeeScript provides + splats ..., both for function definition as well as invocation, + making variable numbers of arguments a little bit more palatable. +

+ <%= code_for('splats', true) %> + +

+ Arguments are Arrays + If you reference the arguments object directly, it will be converted + into a real Array, making all of the + Array methods + available. +

+ <%= code_for('arguments', true) %> + +

+ While Loops + The only low-level loop that CoffeeScript provides is the while loop. The + main difference from JavaScript is that the while loop can be used + as an expression, returning an array containing the result of each iteration + through the loop. +

+ <%= code_for('while', 'lyrics.join("\n")') %> +

+ Other JavaScript loops, such as for loops and do-while loops + can be mimicked by variations on while, but the hope is that you + won't need to do that with CoffeeScript, either because you're using + each (forEach) style iterators, or... +

+ +

+ Comprehensions (Arrays, Objects, and Ranges) + For your looping needs, CoffeeScript provides array comprehensions + similar to Python's. They replace (and compile into) for loops, with + optional guard clauses and the value of the current array index. + Unlike for loops, array comprehensions are expressions, and can be returned + and assigned. They should be able to handle most places where you otherwise + would use a loop, each/forEach, map, or select/filter. +

+ <%= code_for('array_comprehensions') %> +

+ If you know the start and end of your loop, or would like to step through + in fixed-size increments, you can use a range to specify the start and + end of your comprehension. (The long line-breaking "for" definitions in + the compiled JS below allow ranges to count downwards, as well as upwards). +

+ <%= code_for('range_comprehensions', 'countdown') %> +

+ Comprehensions can also be used to iterate over the keys and values in + an object. Use of to signal comprehension over the properties of + an object instead of the values in an array. +

+ <%= code_for('object_comprehensions', 'ages.join(", ")') %> + +

+ Array Slicing and Splicing with Ranges + CoffeeScript borrows Ruby's + range syntax + for extracting slices of arrays. With two dots (3..5), the range + is inclusive: the first argument is the index of the first element in + the slice, and the second is the index of the last one. Three dots signify + a range that excludes the end. +

+ <%= code_for('slices', 'numbers_copy') %> +

+ The same syntax can be used with assignment to replace a segment of an + array with new values (to splice it). +

+ <%= code_for('splices', 'numbers') %> + +

+ Everything is an Expression (at least, as much as possible) + You might have noticed how even though we don't add return statements + to CoffeeScript functions, they nonetheless return their final value. + The CoffeeScript compiler tries to make sure that all statements in the + language can be used as expressions. Watch how the return gets + pushed down into each possible branch of execution, in the function + below. +

+ <%= code_for('expressions', 'eldest') %> +

+ Even though functions will always return their final value, it's both possible + and encouraged to return early from a function body writing out the explicit + return (return value), when you know that you're done. +

+

+ Because variable declarations occur at the top of scope, assignment can + be used within expressions, even for variables that haven't been seen before: +

+ <%= code_for('expressions_assignment', 'six') %> +

+ Things that would otherwise be statements in JavaScript, when used + as part of an expression in CoffeeScript, are converted into expressions + by wrapping them in a closure. This lets you do useful things, like assign + the result of a comprehension to a variable: +

+ <%= code_for('expressions_comprehension', 'globals') %> +

+ As well as silly things, like passing a try/catch statement directly + into a function call: +

+ <%= code_for('expressions_try', true) %> +

+ There are a handful of statements in JavaScript that can't be meaningfully + converted into expressions, namely break, continue, + and return. If you make use of them within a block of code, + CoffeeScript won't try to perform the conversion. +

+ +

+ The Existential Operator + It's a little difficult to check for the existence of a variable in + JavaScript. if (variable) ... comes close, but fails for zero, + the empty string, and false. CoffeeScript's existential operator ? returns true unless + a variable is null or undefined, which makes it analogous + to Ruby's nil? +

+

+ It can also be used for safer conditional assignment than ||= + provides, for cases where you may be handling numbers or strings. +

+ <%= code_for('existence', 'speed') %> +

+ The accessor variant of the existential operator ?. can be used to soak + up null references in a chain of properties. Use it instead + of the dot accessor . in cases where the base value may be null + or undefined. If all of the properties exist then you'll get the expected + result, if the chain is broken, undefined is returned instead of + the TypeError that would be raised otherwise. +

+ <%= code_for('soaks') %> +

+ Soaking up nulls is similar to Ruby's + andand gem, and to the + safe navigation operator + in Groovy. +

+ +

+ Inheritance, and Calling Super from a Subclass + JavaScript's prototypal inheritance has always been a bit of a + brain-bender, with a whole family tree of libraries that provide a cleaner + syntax for classical inheritance on top of JavaScript's prototypes: + Base2, + Prototype.js, + JS.Class, etc. + The libraries provide syntactic sugar, but the built-in inheritance would + be completely usable if it weren't for a couple of small exceptions: + it's awkward to call super (the prototype object's + implementation of the current function), and it's awkward to correctly + set the prototype chain. +

+

+ CoffeeScript provides extends + to help with prototype setup, :: for quick access to an + object's prototype, and converts super() into a call against + the immediate ancestor's method of the same name. +

+ <%= code_for('super', true) %> + +

+ Pattern Matching (Destructuring Assignment) + To make extracting values from complex arrays and objects more convenient, + CoffeeScript implements ECMAScript Harmony's proposed + destructuring assignment + syntax. When you assign an array or object literal to a value, CoffeeScript + breaks up and matches both sides against each other, assigning the values + on the right to the variables on the left. In the simplest case, it can be + used for parallel assignment: +

+ <%= code_for('parallel_assignment', 'bait') %> +

+ But it's also helpful for dealing with functions that return multiple + values. +

+ <%= code_for('multiple_return_values', 'forecast') %> +

+ Pattern matching can be used with any depth of array and object nesting, + to help pull out deeply nested properties. +

+ <%= code_for('object_extraction', 'poet + " — " + street') %> + +

+ Function binding + The fat arrow => can be used to both define a function, and to bind + it to the current value of this, right on the spot. This is helpful + when using callback-based libraries like Prototype or jQuery, for creating + iterator functions to pass to each, or event-handler functions + to use with bind. Functions created with the fat arrow are able to access + properties of the this where they're defined. +

+ <%= code_for('fat_arrow') %> + +

+ Embedded JavaScript + Hopefully, you'll never need to use it, but if you ever need to intersperse + snippets of JavaScript within your CoffeeScript, you can + use backticks to pass it straight through. +

+ <%= code_for('embedded', 'hi()') %> + +

+ Switch/When/Else + Switch statements in JavaScript are rather broken. You can only + do comparisons based on string equality, and need to remember to break at the end of + every case statement to avoid accidentally falling through to + the default case. CoffeeScript compiles switch statements into JavaScript if-else chains, allowing you to + compare any object (via ===), preventing fall-through, and resulting + in a returnable, assignable expression. The format is: switch condition, + when clauses, else the default case. +

+

+ As in Ruby, switch statements in CoffeeScript can take multiple + values for each when clause. If any of the values match, the clause + runs. +

+ <%= code_for('switch') %> + +

+ Try/Catch/Finally + Try/catch statements are just about the same as JavaScript (although + they work as expressions). +

+ <%= code_for('try') %> + +

+ Chained Comparisons + CoffeeScript borrows + chained comparisons + from Python — making it easy to test if a value falls within a + certain range. +

+ <%= code_for('comparisons', 'healthy') %> + +

+ Multiline Strings and Heredocs + Multiline strings are allowed in CoffeeScript. +

+ <%= code_for('strings', 'moby_dick') %> +

+ Heredocs can be used to hold formatted or indentation-sensitive text + (or, if you just don't feel like escaping quotes and apostrophes). The + indentation level that begins the heredoc is maintained throughout, so + you can keep it all aligned with the body of your code. +

+ <%= code_for('heredocs') %> + +

Resources

+ + + +

Change Log

+ +

+ 0.3.2 + @property is now a shorthand for this.property.
+ Switched the default JavaScript engine from Narwhal to Node.js. Pass + the --narwhal flag if you'd like to continue using it. +

+ +

+ 0.3.0 + CoffeeScript 0.3 includes major syntax changes: +
+ The function symbol was changed to + ->, and the bound function symbol is now =>. +
+ Parameter lists in function definitions must now be wrapped in parentheses. +
+ Added property soaking, with the ?. operator. +
+ Made parentheses optional, when invoking functions with arguments. +
+ Removed the obsolete block literal syntax. +

+ +

+ 0.2.6 + Added Python-style chained comparisons, the conditional existence + operator ?=, and some examples from Beautiful Code. + Bugfixes relating to statement-to-expression conversion, arguments-to-array + conversion, and the TextMate syntax highlighter. +

+ +

+ 0.2.5 + The conditions in switch statements can now take multiple values at once — + If any of them are true, the case will run. Added the long arrow ==>, + which defines and immediately binds a function to this. While loops can + now be used as expressions, in the same way that comprehensions can. Splats + can be used within pattern matches to soak up the rest of an array. +

+ +

+ 0.2.4 + Added ECMAScript Harmony style destructuring assignment, for dealing with + extracting values from nested arrays and objects. Added indentation-sensitive + heredocs for nicely formatted strings or chunks of code. +

+ +

+ 0.2.3 + Axed the unsatisfactory ino keyword, replacing it with of for + object comprehensions. They now look like: for prop, value of object. +

+ +

+ 0.2.2 + When performing a comprehension over an object, use ino, instead + of in, which helps us generate smaller, more efficient code at + compile time. +
+ Added :: as a shorthand for saying .prototype. +
+ The "splat" symbol has been changed from a prefix asterisk *, to + a postfix ellipsis ... +
+ Added JavaScript's in operator, + empty return statements, and empty while loops. +
+ Constructor functions that start with capital letters now include a + safety check to make sure that the new instance of the object is returned. +
+ The extends keyword now functions identically to goog.inherits + in Google's Closure Library. +

+ +

+ 0.2.1 + Arguments objects are now converted into real arrays when referenced. +

+ +

+ 0.2.0 + Major release. Significant whitespace. Better statement-to-expression + conversion. Splats. Splice literals. Object comprehensions. Blocks. + The existential operator. Many thanks to all the folks who posted issues, + with special thanks to + Liam O'Connor-Davis for whitespace + and expression help. +

+ +

+ 0.1.6 + Bugfix for running coffee --interactive and --run + from outside of the CoffeeScript directory. Bugfix for nested + function/if-statements. +

+ +

+ 0.1.5 + Array slice literals and array comprehensions can now both take Ruby-style + ranges to specify the start and end. JavaScript variable declaration is + now pushed up to the top of the scope, making all assignment statements into + expressions. You can use \ to escape newlines. + The coffee-script command is now called coffee. +

+ +

+ 0.1.4 + The official CoffeeScript extension is now .coffee instead of + .cs, which properly belongs to + C#. + Due to popular demand, you can now also use = to assign. Unlike + JavaScript, = can also be used within object literals, interchangeably + with :. Made a grammatical fix for chained function calls + like func(1)(2)(3)(4). Inheritance and super no longer use + __proto__, so they should be IE-compatible now. +

+ +

+ 0.1.3 + The coffee command now includes --interactive, + which launches an interactive CoffeeScript session, and --run, + which directly compiles and executes a script. Both options depend on a + working installation of Narwhal. + The aint keyword has been replaced by isnt, which goes + together a little smoother with is. + Quoted strings are now allowed as identifiers within object literals: eg. + {"5+5": 10}. + All assignment operators now use a colon: +:, -:, + *:, etc. +

+ +

+ 0.1.2 + Fixed a bug with calling super() through more than one level of + inheritance, with the re-addition of the extends keyword. + Added experimental Narwhal + support (as a Tusk package), contributed by + Tom Robinson, including + bin/cs as a CoffeeScript REPL and interpreter. + New --no-wrap option to suppress the safety function + wrapper. +

+ +

+ 0.1.1 + Added instanceof and typeof as operators. +

+ +

+ 0.1.0 + Initial CoffeeScript release. +

+ +
+ + + + + + + + + + + + diff --git a/index.html b/index.html index dc00e167..1f6b44e8 100644 --- a/index.html +++ b/index.html @@ -10,11 +10,49 @@ + +
+ +
+ + +
-

CoffeeScript

-

CoffeeScript is a little language that compiles into JavaScript. Think of it as JavaScript's less ostentatious kid brother — the same genes, @@ -40,39 +78,10 @@ 0.3.2

-

Table of Contents

- -

- Mini Overview
- Installation and Usage
- Try CoffeeScript
- Significant Whitespace
- Functions and Invocation
- Assignment
- Objects and Arrays
- Lexical Scoping and Variable Safety
- Conditionals, Ternaries, and Conditional Assignment
- Aliases
- Splats...
- Arguments are Arrays
- While Loops
- Comprehensions (Arrays, Objects, and Ranges)
- Array Slicing and Splicing with Ranges
- Everything is an Expression
- The Existential Operator
- Inheritance, and Calling Super from a Subclass
- Pattern Matching
- Function Binding
- Embedded JavaScript
- Switch/When/Else
- Try/Catch/Finally
- Chained Comparisons
- Multiline Strings and Heredocs
- Resources
- Change Log
-

- -

Mini Overview

+

+ + Mini Overview +

CoffeeScript on the left, compiled JavaScript output on the right.

@@ -202,7 +211,10 @@ cubed_list = (function() { examples folder.

-

Installation and Usage

+

+ + Installation and Usage +

The CoffeeScript compiler is written in pure Ruby, and is available @@ -322,7 +334,10 @@ coffee --interactive coffee --watch --lint experimental.coffee coffee --print app/scripts/*.coffee > concatenation.js -

Try CoffeeScript

+

+ + Try CoffeeScript +

Here's a live version of the CoffeeScript compiler, running within @@ -353,7 +368,8 @@ print reverse 'tpircseeffoc'

-

+

+ Significant Whitespace CoffeeScript uses Python-style significant whitespace: You don't need to use semicolons ; to terminate expressions, ending @@ -375,7 +391,8 @@ print reverse 'tpircseeffoc' as long as CoffeeScript can determine that the line hasn't finished yet.

-

+

+ Functions and Invocation Functions are defined by a list of parameters, an arrow, and the function body. The empty function looks like this: ->. All @@ -403,7 +420,8 @@ cube = function cube(x) { ((x) -> x * x)

-

+

+ Assignment Use a colon : to assign, as in JSON. Equal signs are only needed for @@ -424,7 +442,8 @@ difficulty = 0.5; lexical scope, so that assignment may always be performed within expressions.

-

+

+ Objects and Arrays Object and Array literals look very similar to their JavaScript cousins. When you spread out each assignment on a separate line, the commas are @@ -463,7 +482,8 @@ ages = { matrix = [1, 0, 1, 0, 0, 1, 1, 1, 0]; ;alert(song.join(","));'>run: song.join(",")

-

+

+ Lexical Scoping and Variable Safety The CoffeeScript compiler takes care to make sure that all of your variables are properly declared within lexical scope — you never need to write @@ -514,7 +534,8 @@ new_num = change_numbers(); CommonJS and the browser: root: exports ? this

-

+

+ Conditionals, Ternaries, and Conditional Assignment If/else statements can be written without the use of parentheses and curly brackets. As with functions and other block expressions, @@ -552,7 +573,8 @@ expensive = expensive || -

+

+ Aliases Because the == operator frequently causes undesirable coercion, is intransitive, and has a different meaning than in other languages, @@ -606,7 +628,8 @@ car.speed < speed_limit ? accelerate() : print("My name is " + this.name);

-

+

+ Splats... The JavaScript arguments object is a useful way to work with functions that accept variable numbers of arguments. CoffeeScript provides @@ -668,7 +691,8 @@ alert("Silver: " + silver); alert("The Field: " + the_field); ;'>run
-

+

+ Arguments are Arrays If you reference the arguments object directly, it will be converted into a real Array, making all of the @@ -693,7 +717,8 @@ backwards = function backwards() { backwards("stairway", "to", "heaven"); ;'>run
-

+

+ While Loops The only low-level loop that CoffeeScript provides is the while loop. The main difference from JavaScript is that the while loop can be used @@ -758,7 +783,8 @@ One fell out and bumped his head."); each (forEach) style iterators, or...

-

+

+ Comprehensions (Arrays, Objects, and Ranges) For your looping needs, CoffeeScript provides array comprehensions similar to Python's. They replace (and compile into) for loops, with @@ -891,7 +917,8 @@ ages = (function() { }).call(this); ;alert(ages.join(", "));'>run: ages.join(", ")
-

+

+ Array Slicing and Splicing with Ranges CoffeeScript borrows Ruby's range syntax @@ -932,7 +959,8 @@ numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; numbers.splice.apply(numbers, [3, 6 - 3 + 1].concat([-3, -4, -5, -6])); ;alert(numbers);'>run: numbers
-

+

+ Everything is an Expression (at least, as much as possible) You might have noticed how even though we don't add return statements to CoffeeScript functions, they nonetheless return their final value. @@ -1050,7 +1078,8 @@ globals = (function() { CoffeeScript won't try to perform the conversion.

-

+

+ The Existential Operator It's a little difficult to check for the existence of a variable in JavaScript. if (variable) ... comes close, but fails for zero, @@ -1100,7 +1129,8 @@ speed = (typeof speed !== "undefined" && speed !== null) ? speed : 140; in Groovy.

-

+

+ Inheritance, and Calling Super from a Subclass JavaScript's prototypal inheritance has always been a bit of a brain-bender, with a whole family tree of libraries that provide a cleaner @@ -1226,7 +1256,8 @@ sam.move(); tom.move(); ;'>run
-

+

+ Pattern Matching (Destructuring Assignment) To make extracting values from complex arrays and objects more convenient, CoffeeScript implements ECMAScript Harmony's proposed @@ -1330,7 +1361,8 @@ street = _c[0]; city = _c[1]; ;alert(poet + " — " + street);'>run: poet + " — " + street
-

+

+ Function binding The fat arrow => can be used to both define a function, and to bind it to the current value of this, right on the spot. This is helpful @@ -1360,7 +1392,8 @@ Account = function
-

+

+ Embedded JavaScript Hopefully, you'll never need to use it, but if you ever need to intersperse snippets of JavaScript within your CoffeeScript, you can @@ -1381,7 +1414,8 @@ return [document.title, "Hello JavaScript"].join(": "); }; ;alert(hi());'>run: hi()
-

+

+ Switch/When/Else Switch statements in JavaScript are rather broken. You can only do comparisons based on string equality, and need to remember to break at the end of @@ -1424,7 +1458,8 @@ return [document.title, "Hello JavaScript"].join(": "); }
-

+

+ Try/Catch/Finally Try/catch statements are just about the same as JavaScript (although they work as expressions). @@ -1446,7 +1481,8 @@ return [document.title, "Hello JavaScript"].join(": "); }
-

+

+ Chained Comparisons CoffeeScript borrows chained comparisons @@ -1466,7 +1502,8 @@ cholesterol = 127; healthy = (200 > cholesterol) && (cholesterol > 60); ;alert(healthy);'>run: healthy
-

+

+ Multiline Strings and Heredocs Multiline strings are allowed in CoffeeScript.

@@ -1508,7 +1545,10 @@ world..."; html = "<strong>\n cup of coffeescript\n</strong>";
-

Resources

+

+ + Resources +

-

Change Log

+

+ + Change Log +

0.3.2