uehaj's blog

Grな日々 - GroovyとかGrailsとかElmとかRustとかHaskellとかReactとかFregeとかJavaとか -

GroovyServの小技シリーズ6 Groovyコードの保存時に自動的にコンパイルエラーチェック(ただしEmacsに限る)

Eclipseとかでは常識ですが、あるいはflymakeを適用したruby-modeでもそうなってますが、Groovyソースを保存したときにgroovycをかけるというもの。基本的なエラーは見つけてくれるので便利。

もちろん、今までのgroovycでもできた訳ですけど、遅い。毎回保存するときに実行するには、正直遅いです。でもGroovyServがあれば実用的。

(8/14 22:14修正)
前回の、「現在のバッファをgroovycientで実行する」と合わせてみました。shell-commandだけじゃなくてcompileと組み合わせてるのでエラー行にジャンプもできます。

;;
;; Groovy support functions
;;
(defvar groovy-command "groovyclient %f"
  "groovy or compatible command. %f means buffer-file")

(defvar groovyc-command "groovyclient -e 'org.codehaus.groovy.tools.FileSystemCompiler.main(args)' -- %f"
  "groovyc or compatible command. %f means buffer-file")

(setq groovy-command-line nil)

(defun groovy-execute-argument()
  (if (null groovy-command-line)
      (setq groovy-command-line groovy-command))
  (setq groovy-command-line
        (read-string "Groovy command: " groovy-command-line))
  (list groovy-command-line))

(defun groovy-replace-command (template file)
  (if (string-match "%f" template)
      (while (string-match "%f" template)
        (setq template
              (replace-match file t t template nil))))
  template)

(defun groovy-execute-buffer-file (arg)
  "Execute the groovy code of this buffer."
  (interactive (groovy-execute-argument))
  (save-some-buffers)
  (compile
   (groovy-replace-command
    groovy-command-line
    (buffer-file-name))))

(defun groovy-save-buffer-file ()
  (if (equal ""
             (shell-command-to-string
              (groovy-replace-command
               groovyc-command
               (buffer-file-name))))
      (if (get-buffer-window "*compilation*")
          (delete-window (get-buffer-window "*compilation*")))
    (compile
     (groovy-replace-command
      groovyc-command
      (buffer-file-name)))))

(add-hook 'groovy-mode-hook
          (lambda () (define-key groovy-mode-map "\C-cm" 'groovy-execute-buffer-file)))

(add-hook 'after-save-hook
          (function
           (lambda ()
             (if (eq major-mode 'groovy-mode)
                 (groovy-save-buffer-file)))))

どなたかflymakeにしてほしい。