]> code.delx.au - gnu-emacs-elpa/blob - packages/coffee-mode/coffee-mode.el
Update infrastructure for Git.
[gnu-emacs-elpa] / packages / coffee-mode / coffee-mode.el
1 ;;; coffee-mode.el --- Major mode for CoffeeScript files
2
3 ;; Copyright (C) 2010-2012 Free Software Foundation, Inc.
4
5 ;; Version: 0.4.1
6 ;; Keywords: CoffeeScript major mode
7 ;; Author: Chris Wanstrath <chris@ozmm.org>
8 ;; URL: http://github.com/defunkt/coffee-mode
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published
14 ;; by the Free Software Foundation, either version 3 of the License,
15 ;; or (at your option) any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful, but
18 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 ;; General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24
25 ;;; Commentary
26
27 ;; CoffeeScript mode is an Emacs major mode for [CoffeeScript][cs],
28 ;; unfancy JavaScript. It provides syntax highlighting, indentation
29 ;; support, imenu support, a menu bar, and a few cute commands.
30
31 ;; Installing this package enables CoffeeScript mode for file named
32 ;; *.coffee and Cakefile.
33
34 ;; Commands:
35
36 ;; M-x coffee-compile-file compiles the current file as a JavaScript
37 ;; file. Operating on "basic.coffee" and running this command will
38 ;; save a "basic.js" in the same directory. Subsequent runs will
39 ;; overwrite the file.
40 ;;
41 ;; If there are compilation errors and we the compiler have returned a
42 ;; line number to us for the first error, the point is moved to that
43 ;; line, so you can investigate. If this annoys you, you can set
44 ;; `coffee-compile-jump-to-error` to `nil`.
45 ;;
46 ;; M-x coffee-compile-buffer compiles the current buffer to JavaScript
47 ;; using the command specified by the `coffee-command` variable, and
48 ;; opens the contents in a new buffer using the mode configured for
49 ;; ".js" files.
50 ;;
51 ;; M-x coffee-compile-region compiles the selected region to
52 ;; JavaScript using the same configuration variables as
53 ;; `coffee-compile-buffer`.
54 ;;
55 ;; `C-c C-o C-s' (coffee-cos-mode) toggles a minor mode implementing
56 ;; "compile-on-save" behavior.
57 ;;
58 ;; M-x coffee-repl starts a repl via `coffee-command` in a new buffer.
59
60 ;; Options:
61 ;;
62 ;; `coffee-tab-width' - Tab width to use when indenting.
63 ;; `coffee-command' - CoffeeScript command for evaluating code.
64 ;; Must be in your path.
65 ;; `coffee-args-repl' - Command line arguments for `coffee-command'
66 ;; when starting a REPL.
67 ;; `coffee-args-compile' - Arguments for `coffee-command'
68 ;; when compiling a file.
69 ;; `coffee-compiled-buffer-name' - Name of the scratch buffer used
70 ;; when compiling CoffeeScript.
71 ;; `coffee-compile-jump-to-error' - Whether to jump to the first error
72 ;; if compilation fails.
73
74 ;; Please file bugs at <http://github.com/defunkt/coffee-mode/issues>
75
76 ;;; Code:
77
78 (require 'comint)
79 (require 'easymenu)
80 (require 'font-lock)
81
82 (eval-when-compile
83 (require 'cl))
84
85 ;;
86 ;; Customizable Variables
87 ;;
88
89 (defconst coffee-mode-version "0.4.1"
90 "The version of `coffee-mode'.")
91
92 (defgroup coffee nil
93 "A CoffeeScript major mode."
94 :group 'languages)
95
96 (defcustom coffee-tab-width tab-width
97 "The tab width to use when indenting."
98 :type 'integer
99 :group 'coffee)
100
101 (defcustom coffee-command "coffee"
102 "The CoffeeScript command used for evaluating code."
103 :type 'string
104 :group 'coffee)
105
106 (defcustom js2coffee-command "js2coffee"
107 "The js2coffee command used for evaluating code."
108 :type 'string
109 :group 'coffee)
110
111 (defcustom coffee-args-repl '("-i")
112 "The arguments to pass to `coffee-command' to start a REPL."
113 :type 'list
114 :group 'coffee)
115
116 (defcustom coffee-args-compile '("-c")
117 "The arguments to pass to `coffee-command' to compile a file."
118 :type 'list
119 :group 'coffee)
120
121 (defcustom coffee-compiled-buffer-name "*coffee-compiled*"
122 "The name of the scratch buffer used for compiled CoffeeScript."
123 :type 'string
124 :group 'coffee)
125
126 (defcustom coffee-compile-jump-to-error t
127 "Whether to jump to the first error if compilation fails.
128 Please note that the coffee compiler doesn't always give a line
129 number for the issue and in that case it is not possible to jump
130 to the error."
131 :type 'boolean
132 :group 'coffee)
133
134 (defcustom coffee-watch-buffer-name "*coffee-watch*"
135 "The name of the scratch buffer used when using the --watch flag
136 with CoffeeScript."
137 :type 'string
138 :group 'coffee)
139
140 (defcustom coffee-mode-hook nil
141 "Hook called by `coffee-mode'."
142 :type 'hook
143 :group 'coffee)
144
145 (defvar coffee-mode-map (make-keymap)
146 "Keymap for CoffeeScript major mode.")
147
148 ;;
149 ;; Commands
150 ;;
151
152 (defun coffee-repl ()
153 "Launch a CoffeeScript REPL using `coffee-command' as an inferior mode."
154 (interactive)
155
156 (unless (comint-check-proc "*CoffeeREPL*")
157 (set-buffer
158 (apply 'make-comint "CoffeeREPL"
159 coffee-command nil coffee-args-repl)))
160
161 (pop-to-buffer "*CoffeeREPL*"))
162
163 (defun coffee-compiled-file-name (&optional filename)
164 "Returns the name of the JavaScript file compiled from a CoffeeScript file.
165 If FILENAME is omitted, the current buffer's file name is used."
166 (concat (file-name-sans-extension (or filename (buffer-file-name))) ".js"))
167
168 (defun coffee-compile-file ()
169 "Compiles and saves the current file to disk."
170 (interactive)
171 (let ((compiler-output (shell-command-to-string (coffee-command-compile (buffer-file-name)))))
172 (if (string= compiler-output "")
173 (message "Compiled and saved %s" (coffee-compiled-file-name))
174 (let* ((msg (car (split-string compiler-output "[\n\r]+")))
175 (line (and (string-match "on line \\([0-9]+\\)" msg)
176 (string-to-number (match-string 1 msg)))))
177 (message msg)
178 (when (and coffee-compile-jump-to-error line (> line 0))
179 (goto-char (point-min))
180 (forward-line (1- line)))))))
181
182 (defun coffee-compile-buffer ()
183 "Compiles the current buffer and displays the JavaScript in a buffer
184 called `coffee-compiled-buffer-name'."
185 (interactive)
186 (save-excursion
187 (coffee-compile-region (point-min) (point-max))))
188
189 (defun coffee-compile-region (start end)
190 "Compiles a region and displays the JavaScript in a buffer called
191 `coffee-compiled-buffer-name'."
192 (interactive "r")
193
194 (let ((buffer (get-buffer coffee-compiled-buffer-name)))
195 (when buffer
196 (kill-buffer buffer)))
197
198 (apply (apply-partially 'call-process-region start end coffee-command nil
199 (get-buffer-create coffee-compiled-buffer-name)
200 nil)
201 (append coffee-args-compile (list "-s" "-p")))
202 (switch-to-buffer (get-buffer coffee-compiled-buffer-name))
203 (let ((buffer-file-name "tmp.js")) (set-auto-mode))
204 (goto-char (point-min)))
205
206 (defun coffee-js2coffee-replace-region (start end)
207 "Convert JavaScript in the region into CoffeeScript."
208 (interactive "r")
209
210 (let ((buffer (get-buffer coffee-compiled-buffer-name)))
211 (when buffer
212 (kill-buffer buffer)))
213
214 (call-process-region start end
215 js2coffee-command nil
216 (current-buffer))
217 (delete-region start end))
218
219 (defun coffee-version ()
220 "Show the `coffee-mode' version in the echo area."
221 (interactive)
222 (message (concat "coffee-mode version " coffee-mode-version)))
223
224 (defun coffee-watch (dir-or-file)
225 "Run `coffee-run-cmd' with the --watch flag on a directory or file."
226 (interactive "fDirectory or File: ")
227 (let ((coffee-compiled-buffer-name coffee-watch-buffer-name)
228 (args (mapconcat 'identity (append coffee-args-compile (list "--watch" (expand-file-name dir-or-file))) " ")))
229 (coffee-run-cmd args)))
230
231 ;;
232 ;; Menubar
233 ;;
234
235 (easy-menu-define coffee-mode-menu coffee-mode-map
236 "Menu for CoffeeScript mode"
237 '("CoffeeScript"
238 ["Compile File" coffee-compile-file]
239 ["Compile Buffer" coffee-compile-buffer]
240 ["Compile Region" coffee-compile-region]
241 ["REPL" coffee-repl]
242 "---"
243 ["Version" coffee-show-version]
244 ))
245
246 ;;
247 ;; Define Language Syntax
248 ;;
249
250 ;; String literals
251 (defvar coffee-string-regexp "\"\\([^\\]\\|\\\\.\\)*?\"\\|'\\([^\\]\\|\\\\.\\)*?'")
252
253 ;; Instance variables (implicit this)
254 (defvar coffee-this-regexp "@\\(\\w\\|_\\)*\\|this")
255
256 ;; Prototype::access
257 (defvar coffee-prototype-regexp "\\(\\(\\w\\|\\.\\|_\\| \\|$\\)+?\\)::\\(\\(\\w\\|\\.\\|_\\| \\|$\\)+?\\):")
258
259 ;; Assignment
260 (defvar coffee-assign-regexp "\\(\\(\\w\\|\\.\\|_\\|$\\)+?\s*\\):")
261
262 ;; Lambda
263 (defvar coffee-lambda-regexp "\\((.+)\\)?\\s *\\(->\\|=>\\)")
264
265 ;; Namespaces
266 (defvar coffee-namespace-regexp "\\b\\(class\\s +\\(\\S +\\)\\)\\b")
267
268 ;; Booleans
269 (defvar coffee-boolean-regexp "\\b\\(true\\|false\\|yes\\|no\\|on\\|off\\|null\\|undefined\\)\\b")
270
271 ;; Regular Expressions
272 (defvar coffee-regexp-regexp "\\/\\(\\\\.\\|\\[\\(\\\\.\\|.\\)+?\\]\\|[^/]\\)+?\\/")
273
274 ;; JavaScript Keywords
275 (defvar coffee-js-keywords
276 '("if" "else" "new" "return" "try" "catch"
277 "finally" "throw" "break" "continue" "for" "in" "while"
278 "delete" "instanceof" "typeof" "switch" "super" "extends"
279 "class" "until" "loop"))
280
281 ;; Reserved keywords either by JS or CS.
282 (defvar coffee-js-reserved
283 '("case" "default" "do" "function" "var" "void" "with"
284 "const" "let" "debugger" "enum" "export" "import" "native"
285 "__extends" "__hasProp"))
286
287 ;; CoffeeScript keywords.
288 (defvar coffee-cs-keywords
289 '("then" "unless" "and" "or" "is"
290 "isnt" "not" "of" "by" "where" "when"))
291
292 ;; Regular expression combining the above three lists.
293 (defvar coffee-keywords-regexp (regexp-opt
294 (append
295 coffee-js-reserved
296 coffee-js-keywords
297 coffee-cs-keywords) 'words))
298
299
300 ;; Create the list for font-lock. Each class of keyword is given a
301 ;; particular face.
302 (defvar coffee-font-lock-keywords
303 ;; *Note*: order below matters. `coffee-keywords-regexp' goes last
304 ;; because otherwise the keyword "state" in the function
305 ;; "state_entry" would be highlighted.
306 `((,coffee-string-regexp . font-lock-string-face)
307 (,coffee-this-regexp . font-lock-variable-name-face)
308 (,coffee-prototype-regexp . font-lock-variable-name-face)
309 (,coffee-assign-regexp . font-lock-type-face)
310 (,coffee-regexp-regexp . font-lock-constant-face)
311 (,coffee-boolean-regexp . font-lock-constant-face)
312 (,coffee-keywords-regexp . font-lock-keyword-face)))
313
314 ;;
315 ;; Helper Functions
316 ;;
317
318 (defun coffee-comment-dwim (arg)
319 "Comment or uncomment current line or region in a smart way.
320 For details, see `comment-dwim'."
321 (interactive "*P")
322 (require 'newcomment)
323 (let ((deactivate-mark nil) (comment-start "#") (comment-end ""))
324 (comment-dwim arg)))
325
326 (defun coffee-command-compile (file-name)
327 "Run `coffee-command' to compile FILE."
328 (let ((full-file-name (expand-file-name file-name)))
329 (mapconcat 'identity (append (list coffee-command) coffee-args-compile (list full-file-name)) " ")))
330
331 (defun coffee-run-cmd (args)
332 "Run `coffee-command' with the given arguments, and display the
333 output in a compilation buffer."
334 (interactive "sArguments: ")
335 (let ((compilation-buffer-name-function (lambda (this-mode)
336 (generate-new-buffer-name coffee-compiled-buffer-name))))
337 (compile (concat coffee-command " " args))))
338
339 ;;
340 ;; imenu support
341 ;;
342
343 ;; This is a pretty naive but workable way of doing it. First we look
344 ;; for any lines that starting with `coffee-assign-regexp' that include
345 ;; `coffee-lambda-regexp' then add those tokens to the list.
346 ;;
347 ;; Should cover cases like these:
348 ;;
349 ;; minus: (x, y) -> x - y
350 ;; String::length: -> 10
351 ;; block: ->
352 ;; print('potion')
353 ;;
354 ;; Next we look for any line that starts with `class' or
355 ;; `coffee-assign-regexp' followed by `{` and drop into a
356 ;; namespace. This means we search one indentation level deeper for
357 ;; more assignments and add them to the alist prefixed with the
358 ;; namespace name.
359 ;;
360 ;; Should cover cases like these:
361 ;;
362 ;; class Person
363 ;; print: ->
364 ;; print 'My name is ' + this.name + '.'
365 ;;
366 ;; class Policeman extends Person
367 ;; constructor: (rank) ->
368 ;; @rank: rank
369 ;; print: ->
370 ;; print 'My name is ' + this.name + " and I'm a " + this.rank + '.'
371 ;;
372 ;; TODO:
373 ;; app = {
374 ;; window: {width: 200, height: 200}
375 ;; para: -> 'Welcome.'
376 ;; button: -> 'OK'
377 ;; }
378
379 (defun coffee-imenu-create-index ()
380 "Create an imenu index of all methods in the buffer."
381 (interactive)
382
383 ;; This function is called within a `save-excursion' so we're safe.
384 (goto-char (point-min))
385
386 (let ((index-alist '()) assign pos indent ns-name ns-indent)
387 ;; Go through every assignment that includes -> or => on the same
388 ;; line or starts with `class'.
389 (while (re-search-forward
390 (concat "^\\(\\s *\\)"
391 "\\("
392 coffee-assign-regexp
393 ".+?"
394 coffee-lambda-regexp
395 "\\|"
396 coffee-namespace-regexp
397 "\\)")
398 (point-max)
399 t)
400
401 ;; If this is the start of a new namespace, save the namespace's
402 ;; indentation level and name.
403 (when (match-string 8)
404 ;; Set the name.
405 (setq ns-name (match-string 8))
406
407 ;; If this is a class declaration, add :: to the namespace.
408 (setq ns-name (concat ns-name "::"))
409
410 ;; Save the indentation level.
411 (setq ns-indent (length (match-string 1))))
412
413 ;; If this is an assignment, save the token being
414 ;; assigned. `Please.print:` will be `Please.print`, `block:`
415 ;; will be `block`, etc.
416 (when (setq assign (match-string 3))
417 ;; The position of the match in the buffer.
418 (setq pos (match-beginning 3))
419
420 ;; The indent level of this match
421 (setq indent (length (match-string 1)))
422
423 ;; If we're within the context of a namespace, add that to the
424 ;; front of the assign, e.g.
425 ;; constructor: => Policeman::constructor
426 (when (and ns-name (> indent ns-indent))
427 (setq assign (concat ns-name assign)))
428
429 ;; Clear the namespace if we're no longer indented deeper
430 ;; than it.
431 (when (and ns-name (<= indent ns-indent))
432 (setq ns-name nil)
433 (setq ns-indent nil))
434
435 ;; Add this to the alist. Done.
436 (push (cons assign pos) index-alist)))
437
438 ;; Return the alist.
439 index-alist))
440
441 ;;
442 ;; Indentation
443 ;;
444
445 ;;; The theory is explained in the README.
446
447 (defun coffee-indent-line ()
448 "Indent current line as CoffeeScript."
449 (interactive)
450
451 (if (= (point) (point-at-bol))
452 (insert-tab)
453 (save-excursion
454 (let ((prev-indent (coffee-previous-indent))
455 (cur-indent (current-indentation)))
456 ;; Shift one column to the left
457 (beginning-of-line)
458 (insert-tab)
459
460 (when (= (point-at-bol) (point))
461 (forward-char coffee-tab-width))
462
463 ;; We're too far, remove all indentation.
464 (when (> (- (current-indentation) prev-indent) coffee-tab-width)
465 (backward-to-indentation 0)
466 (delete-region (point-at-bol) (point)))))))
467
468 (defun coffee-previous-indent ()
469 "Return the indentation level of the previous non-blank line."
470 (save-excursion
471 (forward-line -1)
472 (if (bobp)
473 0
474 (progn
475 (while (and (looking-at "^[ \t]*$") (not (bobp))) (forward-line -1))
476 (current-indentation)))))
477
478 (defun coffee-newline-and-indent ()
479 "Insert a newline and indent it to the same level as the previous line."
480 (interactive)
481
482 ;; Remember the current line indentation level,
483 ;; insert a newline, and indent the newline to the same
484 ;; level as the previous line.
485 (let ((prev-indent (current-indentation)) (indent-next nil))
486 (delete-horizontal-space t)
487 (newline)
488 (insert-tab (/ prev-indent coffee-tab-width))
489
490 ;; We need to insert an additional tab because the last line was special.
491 (when (coffee-line-wants-indent)
492 (insert-tab)))
493
494 ;; Last line was a comment so this one should probably be,
495 ;; too. Makes it easy to write multi-line comments (like the one I'm
496 ;; writing right now).
497 (when (coffee-previous-line-is-comment)
498 (insert "# ")))
499
500 ;; Indenters help determine whether the current line should be
501 ;; indented further based on the content of the previous line. If a
502 ;; line starts with `class', for instance, you're probably going to
503 ;; want to indent the next line.
504
505 (defvar coffee-indenters-bol '("class" "for" "if" "try")
506 "Keywords or syntax whose presence at the start of a line means the
507 next line should probably be indented.")
508
509 (defun coffee-indenters-bol-regexp ()
510 "Builds a regexp out of `coffee-indenters-bol' words."
511 (regexp-opt coffee-indenters-bol 'words))
512
513 (defvar coffee-indenters-eol '(?> ?{ ?\[)
514 "Single characters at the end of a line that mean the next line
515 should probably be indented.")
516
517 (defun coffee-line-wants-indent ()
518 "Return t if the current line should be indented relative to the
519 previous line."
520 (interactive)
521
522 (save-excursion
523 (let ((indenter-at-bol) (indenter-at-eol))
524 ;; Go back a line and to the first character.
525 (forward-line -1)
526 (backward-to-indentation 0)
527
528 ;; If the next few characters match one of our magic indenter
529 ;; keywords, we want to indent the line we were on originally.
530 (when (looking-at (coffee-indenters-bol-regexp))
531 (setq indenter-at-bol t))
532
533 ;; If that didn't match, go to the back of the line and check to
534 ;; see if the last character matches one of our indenter
535 ;; characters.
536 (when (not indenter-at-bol)
537 (end-of-line)
538
539 ;; Optimized for speed - checks only the last character.
540 (let ((indenters coffee-indenters-eol))
541 (while indenters
542 (if (/= (char-before) (car indenters))
543 (setq indenters (cdr indenters))
544 (setq indenter-at-eol t)
545 (setq indenters nil)))))
546
547 ;; If we found an indenter, return `t'.
548 (or indenter-at-bol indenter-at-eol))))
549
550 (defun coffee-previous-line-is-comment ()
551 "Return t if the previous line is a CoffeeScript comment."
552 (save-excursion
553 (forward-line -1)
554 (coffee-line-is-comment)))
555
556 (defun coffee-line-is-comment ()
557 "Return t if the current line is a CoffeeScript comment."
558 (save-excursion
559 (backward-to-indentation 0)
560 (= (char-after) (string-to-char "#"))))
561
562 ;;
563 ;; Define Major Mode
564 ;;
565
566 ;;;###autoload
567 (define-derived-mode coffee-mode fundamental-mode
568 "Coffee"
569 "Major mode for editing CoffeeScript."
570
571 ;; key bindings
572 (define-key coffee-mode-map (kbd "A-r") 'coffee-compile-buffer)
573 (define-key coffee-mode-map (kbd "A-R") 'coffee-compile-region)
574 (define-key coffee-mode-map (kbd "A-M-r") 'coffee-repl)
575 (define-key coffee-mode-map [remap comment-dwim] 'coffee-comment-dwim)
576 (define-key coffee-mode-map "\C-m" 'coffee-newline-and-indent)
577 (define-key coffee-mode-map "\C-c\C-o\C-s" 'coffee-cos-mode)
578
579 ;; code for syntax highlighting
580 (setq font-lock-defaults '((coffee-font-lock-keywords)))
581
582 ;; perl style comment: "# ..."
583 (modify-syntax-entry ?# "< b" coffee-mode-syntax-table)
584 (modify-syntax-entry ?\n "> b" coffee-mode-syntax-table)
585 (make-local-variable 'comment-start)
586 (setq comment-start "#")
587
588 ;; single quote strings
589 (modify-syntax-entry ?' "\"" coffee-mode-syntax-table)
590
591 ;; indentation
592 (make-local-variable 'indent-line-function)
593 (setq indent-line-function 'coffee-indent-line)
594 (set (make-local-variable 'tab-width) coffee-tab-width)
595
596 ;; imenu
597 (make-local-variable 'imenu-create-index-function)
598 (setq imenu-create-index-function 'coffee-imenu-create-index)
599
600 ;; no tabs
601 (setq indent-tabs-mode nil))
602
603 ;;
604 ;; Compile-on-Save minor mode
605 ;;
606
607 (defvar coffee-cos-mode-line " CoS")
608 (make-variable-buffer-local 'coffee-cos-mode-line)
609
610 (define-minor-mode coffee-cos-mode
611 "Toggle compile-on-save for coffee-mode."
612 :group 'coffee-cos :lighter coffee-cos-mode-line
613 (cond
614 (coffee-cos-mode
615 (add-hook 'after-save-hook 'coffee-compile-file nil t))
616 (t
617 (remove-hook 'after-save-hook 'coffee-compile-file t))))
618
619 (provide 'coffee-mode)
620
621 ;;
622 ;; On Load
623 ;;
624
625 ;; Run coffee-mode for files ending in .coffee.
626 ;;;###autoload
627 (add-to-list 'auto-mode-alist '("\\.coffee$" . coffee-mode))
628 ;;;###autoload
629 (add-to-list 'auto-mode-alist '("Cakefile" . coffee-mode))
630 ;;; coffee-mode.el ends here