スクリプトを手軽に実行

自宅で眠っていたもう一台のサーバを開発用とするための作業で一日を費やしてしまい、結局今日はPHPの勉強がなにもできませんでした。
なので他のネタをひとつ。

下はPerlを勉強している頃に作った関数。
編集中のバッファの内容をそのままスクリプトコマンドに渡す、というもので、M-x compile などとは違い、ファイルを作らなくてもいいところが気に入ってます。
新たな言語を学んでいる時や、ちょっとしたスクリプトを実行したいときに便利です。
(run-script.el)

(defvar run-script-history nil)
(defvar run-script-command nil)
(defvar run-script-argument "")
(defvar run-script-temporary-buffer-name nil)

(make-variable-buffer-local 'run-script-history)
(make-variable-buffer-local 'run-script-command)
(make-variable-buffer-local 'run-script-argument)
(make-variable-buffer-local 'run-script-temporary-buffer-name)

;;;###autoload
(defun run-script ()
  (interactive)
  (when (null run-script-command)
    (error "No script command specified. Set `run-script-command'."))
  (let (command-line
        (src-buf (current-buffer))
        (output-buf (get-buffer-create
                     (format "*%s*"
                             (or run-script-temporary-buffer-name
                                 (concat mode-name " output")))))
        (compilation-process-setup-function 'run-script-process-setup)
        (coding-system-for-read buffer-file-coding-system)
        (coding-system-for-write buffer-file-coding-system)
        (temp-path (expand-file-name (make-temp-name "runscripttmp")
                                     temporary-file-directory))
        (arg run-script-argument))
    (when current-prefix-arg
      (setq arg (read-from-minibuffer "Argument: "
                                      (eval arg) nil nil
                                      '(run-script-history . 1))))
    (setq command-line (format "%s %s %s" run-script-command arg temp-path))
    (unwind-protect
        (progn
          (write-region (point-min) (point-max) temp-path nil 0)
          (shell-command command-line output-buf))
      (delete-file temp-path)
      (pop-to-buffer output-buf)
      (pop-to-buffer src-buf))))

(.emacs)

(autoload 'run-script "run-script" t)


Rubyでしたら、.emacs

(add-hook 'ruby-mode-hook
          '(lambda nil
             (set (make-local-variable 'run-script-command)
                  "ruby")
             (set (make-local-variable 'run-script-argument)
                  "-w")
             (inf-ruby-keys)
             (define-key ruby-mode-map "\M-p" 'run-script)))

というのを加えておきます。

コードを書いていて、ふとFileクラスにはどんなメソッドがあったかな、と思ったときには、おもむろに C-x b して、"qqq"とか適当なバッファ名を入力して(こうすると一時バッファが作られます)、M-x ruby-mode して、

print File.public_methods.sort.join("\n")

と書き、M-p を押してRubyを実行。これでFileクラスのメソッド一覧が結果バッファに表示されます。

PHPの場合なら、.emacsには

(add-hook 'php-mode-user-hook
          (lambda nil
            (set (make-local-variable 'run-script-command)
                 "php")
            (set (make-local-variable 'run-script-temporary-buffer-name)
                 "php output")
            (set (make-local-variable 'run-script-argument)
                 "-f")
            (define-key php-mode-map "\M-p" 'run-script)))

というようにしておきます。