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