Kodama's home / tips.
emacs ruby-mode 漢字コードの指定
ruby スクリプトに漢字が入ったら EUC コードで保存する場合
スクリプト内に coding-system の指定を書き込む方法
スクリプトの開始部分を次のようにする:
#!/usr/local/bin/ruby
# -*- buffer-file-coding-system: euc-japan -*-
# -*- encodings: japanese.euc_jp -*-
emacs ruby-mode-hook に add-hook する方法
ruby-mode を使っていると仮定.
.emacs(GNU Emacs 21.2.1) で次のように指定する.
(Plamo Linux のサンプルで知ったが, 一般的な方法かどうかは不明.)
;; バッファに漢字を新たに書き加えた時の対策 thanks to 鈴木圭一
;;
(defun my-buffer-file-coding-system-fixed-p ()
(let ((buf-base (coding-system-base buffer-file-coding-system)))
(not
(or (and (eq buf-base 'undecided)
(not (eq (coding-system-base
(car (detect-coding-region (point-min) (point-max))))
'undecided)))
(and (eq buf-base (coding-system-base
default-buffer-file-coding-system))
(not (eq (coding-system-base
(car (detect-coding-region (point-min) (point-max))))
'undecided)))))))
(defun my-set-file-coding-system-for-write (cs)
(let ((buf-base (coding-system-base buffer-file-coding-system)))
(unless (or (my-buffer-file-coding-system-fixed-p)
(and (eq buf-base (coding-system-base cs))
(eq (coding-system-eol-type buffer-file-coding-system)
(coding-system-eol-type cs))))
(when (y-or-n-p (format "set coding system to %s instead of %s ? "
cs buffer-file-coding-system))
(set-buffer-file-coding-system cs))))
nil)
(defun my-set-file-coding-system-for-write-quick (cs)
(let ((buf-base (coding-system-base buffer-file-coding-system)))
(unless (or (my-buffer-file-coding-system-fixed-p)
(and (eq buf-base (coding-system-base cs))
(eq (coding-system-eol-type buffer-file-coding-system)
(coding-system-eol-type cs))))
(set-buffer-file-coding-system cs)))
nil)
;; こちらをadd-hookしておくと,バッファに漢字を新たに書き加えた時,
;; どの漢字コードでsaveするか,defaultをcsとして,質問してくれる.
(defun my-set-file-encoding (cs)
(add-hook 'local-write-file-hooks
`(lambda ()
(my-set-file-coding-system-for-write
(quote ,cs)))))
;; こちらをadd-hookしておくと,バッファに漢字を新たに書き加えた時,
;; 速攻でcsな漢字コードでsaveしてくれる.
(defun my-set-file-encoding-quick (cs)
(add-hook 'local-write-file-hooks
`(lambda ()
(my-set-file-coding-system-for-write-quick
(quote ,cs)))))
;; file eocoding as euc-japan in ruby-mode.
(add-hook 'ruby-mode-hook
'(lambda ()
(my-set-file-encoding-quick 'euc-japan)
) t)
Kodama's home / tips.