Hatena::ブログ(Diary)

わからん

2010.12.29

[][] emacs のリージョン内の PHP コードを phpStylist で整形する

これまでに、emacs のリージョンにある Javascript, HTML を整形する方法を紹介しました。今回は、リージョンの PHP コードを phpStylist を利用して整形する方法を解説します*1


まずは、 phpStylist の設定です。http://sourceforge.net/projects/phpstylist/ から zip ファイルをダウンロードします。解凍してできた phpStylist.php、phpStylist.js を ~/bin などのパスの通ったところに配置します。そして、pstyle という名前で 以下の内容のスクリプトを ~/bin 以下に作成します。これはインデント幅を4から2に変更しただけで、PHPのソース整形ツール phpStylist - てつじんにっき と同じ内容です。

#!/bin/sh
php ~/bin/phpStylist.php $1 \
    --indent_size 2 \
    --keep_redundant_lines \
    --space_after_comma \
    --space_around_assignment \
    --align_var_assignment \
    --space_around_comparison \
    --space_around_arithmetic \
    --space_around_logical \
    --space_around_colon_question \
    --line_before_curly_function \
    --space_after_if \
    --else_along_curly \
    --add_missing_braces \
    --line_after_break \
    --space_inside_for \
    --indent_case \
    --vertical_array \
    --align_array_assignment \
    --space_around_double_arrow \
    --space_around_concat \
    --line_before_comment_multi \

実際にシェルで plist ~/hoge.php などと打ち動作が確認できたら、次は、emacs の設定です。dot.emacs に以下の elisp を貼り付けて評価して下さい。

(setq pstyle "~/bin/pstyle")

(defun my-php-format-region (begin end)
  (interactive "r")
  (let ((region-string (buffer-substring-no-properties begin end))
        (temp-file (make-temp-file "my-php-format-region-"))
        (result-buffer "*my-php-format-region*")
        (result-string))
    (save-window-excursion    
      (with-temp-file temp-file
        (insert region-string))
      (shell-command (concat pstyle " " temp-file) result-buffer)
      (with-current-buffer result-buffer
        (unless current-prefix-arg
          (replace-string "<?php " "" nil (point-min) (point-max))
          (replace-string "?>" "" nil (point-min) (point-max)))
        (setq result-string (buffer-substring-no-properties (point-min) (point-max))))
      (delete-file temp-file)
      (kill-buffer result-buffer)
      (kill-region begin end)
      (insert result-string))))

(defalias 'phpf 'my-php-format-region)

これで、整形したい範囲をリージョン選択後に M-x phpf することできれいにフォーマットされたコードに置き換わります。

最後に、動作サンプルを載せておきます。


▼ これをきれいにしたいなら、

f:id:kitokitoki:20101229154803p:image

▼ リージョン選択して M-x phpf と入力します

f:id:kitokitoki:20101229154804p:image

▼ うまくいきました

f:id:kitokitoki:20101229154805p:image

*1:ただし、phpStylist を普通に利用すると <?php タグが挿入される都合上、リージョンの1行目はインデントが崩れてしまいます

はてなユーザーのみコメントできます。はてなへログインもしくは新規登録をおこなってください。

Google