Emacs

Last-modified: 2011-03-23 (水) 13:07:10

自作コード

key configs

全体:keybind

dired/dired-x
etags
カッコ単位でのカーソル移動
navi.el 関数一覧表示のelisp
レジスタ
矩形領域
Emacs-w3m -- an Emacs interface to w3m --: 基本的な使い方

特殊なキーの扱い

Ctrl+hでEmacsのヘルプが見たくない人のための設定 ― ディノオープンラボラトリ

いわゆる特殊キー

  • C-m : RET
  • C-i : TAB
  • C-h : DEL (==<backspace>) ただし、CarbonEmacsなどでそうなっていない場合もある。
  • C-[ : ESC

DELまわりにバインドしたい

  • DELのキーコードは\177なので、これにバインドする。
    (global-set-key "\177" 'backward-delete-char-untabify)
  • C-M-hにバインドする場合
    (global-set-key (kbd "C-M-h") 'backward-kill-ward)
  • C-S-hにバインドする場合
    (global-set-key (kbd "C-S-h") 'backward-delete-char-untabify)

翻訳前の特殊キーにバインドしたい

たとえばC-mの動作を変えずに、RETURNキーにバインドしたい場合。
(global-set-key (kbd "<return>") 'some-function)
backspaceにバインドしたい場合。
(global-set-key (kbd "<backspace>") 'another-function)

kbdはマクロで、その次に与えられたキーシーケンスをemacsの内部キーに翻訳する。たとえば(kbd "C-S-h")を実行すると[33554440]と返される。
ただし、以上の関数はどの環境でも動作するわけではたぶんない。コンソール上などはむずかしそう。

speedbar

左や右にべつのフレームを用意して、そこからフォルダやスクリプト内の関数etcをブラウズ出来る機能
CarbonEmacsでは標準でimenuをスクリプト解析器として使うようになっている。
imenuについてはimenu.el の使い方と応用 ― ありえるえりあ
Emacs の speedbar に関して : miura-takeshi.com

dired補助

diredの空き容量表示

diredのディスク空き容量は、get-free-disk-spaceの関数を利用して表示されている。これにアドバイスを追加することで、GB/MB/kb単位で表示する(標準はつねにkb単位)。
GB級のHDDが標準の現在、kb単位は見にくすぎる。

(defadvice get-free-disk-space (after get-free-disk-gb activate)
 "Return free disk space with GByte order (originally kbyte order)"
 (setq kb (string-to-number ad-return-value)) ; this is reserved variable
 (if (> kb 1024)
     (progn (setq kb (/ kb 1024))
            (if (> kb 1024)
                (setq ad-return-value (format "%.0f GB" (/ kb 1024)))
              (setq ad-return-value (format "%.0f MB" kb))))
   (setq ad-return-value (format "%.0f kB" kb))))

bf-mode

dired上で、ファイルのプレビューのようなことを行うためのminer mode。テキストファイルのみならず、xdoc2txtの利用により、MS Officeのファイルも読めるらしい。

ウィンドウがひとつになる

bf-modeを導入した状態でdiredをたちあげるとwindow分割がなくなってしまう。
このときもとのwindowの状態はbf-mode-window-stackに保存されており、bf-mode-kill-dired関数が呼び出されると元に戻るはずである。
元に戻る条件は、

  • diredにはいったあと、qで終了
  • diredにはいったあと、bf-modeを使用してからqで終了
    戻らない条件は、
  • diredにはいったあと、C-xkでバッファを殺す
  • diredにはいったあと、bf-modeを使用してからC-xkでバッファを殺す
    • 上2つの問題は、C-x kにbf-mode-kill-diredをうわがきバインドすることで解決する。
  • diredでファイルを開く(バッファはそのまま)
    • dired-advertised-find-fileにふさわしい関数をバインドすることで解決するが、そのバッファに戻ってきたときにどうなってしまうかわからないので、find-fileするたびにバッファを殺すか(問題は見当たらない)あきらめるか。

TeX-mode

ネット上で見つけた設定。未実験

;; auctex: japanese-latex-mode
(require 'tex-site)
(require 'tex-jp)
(setq TeX-dafault-mode 'japanese-latex-mode)
(setq-default japanese-LaTeX-default-style "jarticle")
(setq TeX-view-style

     '(("^a5$" "xdvi-ja %d -paper a5")
       ("^landscape$" "xdvi-ja %d -paper a4r -s 4")
       ("." "xdvi-ja %d")))

(setq auto-mode-alist

     ;;; 拡張子とモードの対応
     (append
      '(("\\.tex$" . japanese-latex-mode))
      auto-mode-alist))

(add-hook 'LaTeX-mode-hook 'turn-on-reftex) ; reftex-mode

SGML-mode

  • Carbon Emacsはsgml-mode = xml-modeになっていた。PSGMLとかnXMLとかにくらべて機能は少ないようだ。
    settingがめんどうでもPSGMLなどをつかったほうがよかろう。
  • PSGMLの開発はほぼ停止状態らしい。sourceforgeにプロジェクトが存在するが、最終アップデートは2005年である。
  • nXMLかnXHTMLがよさそう。nXHTMLはnXMLからの派生で、XHTMLやテンプレート言語に強く対応しているそうだ。nXMLも新しくはない。nXHTMLはWindowsとの親和性がよいようだ(グラフィカルなメニューの提供)。
  • 以上3modesはCarbonには標準ではいってました。好きなものえらべ、ってことか。
    めも:installまで終了。site-lisp内のpathを通して、modeをつかってみよう。

windows向け

HOME環境変数を、ホームディレクトリにしたいディレクトリの末尾\なしで設定。その直下に.emacsや.emacs.dを置く。
画面サイズ設定

(progn
 (setq fObj (selected-frame))
 (modify-frame-parameters nil (list (cons 'left (setq lMargin 0))))
 (modify-frame-parameters nil (list (cons 'top (setq tMargin 0))))
 (set-frame-width fObj (setq nCWidth 158))
 (set-frame-height fObj (setq nCHeight 45))
 (split-window-horizontally)
)

調整中・・
最大化なら簡単

(w32-send-sys-command #xf030)

linux向け

xdg-open/gnome-open

macのopenやwindows用のfiberのようなもの
2010-09-15 - mooz deceives you
LinuxでコマンドラインからURLやファイルを開けるxdg-open/gnome-openのメモ (blog@browncat.org)

server-client設定

標準ではemacsは多重起動してしまう。すなわち、他のプログラムからemacsを起動するたびにあたらしいプロセスとしてきどうしている。これではバッファの共有etcがなされなくて不便なので、メインのバッファをサーバに、ほかに起動するときはそれをクライアントとして起動するようにする。

サーバ用設定

個人用の.emacsに次を書く

(server-start)

編集が終わったら、C-x #することでファイルを保存して、emacsclientに終了シグナルを送る。
その他設定項目はあまりない。

クライアント用設定

$EDITOR環境変数など、起動するプログラムを、emacsclient(/usr/bin/emacsclient)に設定。
ただし、編集が終わるのを待たずに終了させたいときは、オプション `-n' や `--no-wait' を使う。

その他のオプションや設定についてはEmacsマニュアルを参照のこと。

TRAMP

Trampでfind-fileしたときにwrong argument listpがでる不具合

私の場合、lcomp(配布元: Navi2ch for Emacs 跡地)との競合が原因だった。
lcompはcompletion用のウィンドウを勝手に消してしまう。find-fileは頼まないのにかってにcompletionの関数を呼び出す。この呼出がfailしてwrong argument: listpのエラーが出ていた。
lcompを使わなければいい。それほど役に立っていた印象はなかったのでそのまま削除して対策とした。

Usage

  • root権限でファイルを開く
    /sudo::/path/to/local/file
    /sudo:root@server:/path/to/remote/file
  • sshでリモートファイルを開く
    /ssh:user@host:/path/to

自動sudo

root所有のファイルを一般ユーザから開くときに自動的にsudoするかどうかを尋ねる。

(defun file-root-p (filename)
 "Return t if file FILENAME created by root."
 (eq 0 (nth 2 (file-attributes filename))))
(defun th-rename-tramp-buffer ()
 (when (file-remote-p (buffer-file-name))
   (rename-buffer
    (format "%s:%s"
            (file-remote-p (buffer-file-name) 'method)
            (buffer-name)))))
(add-hook 'find-file-hook
         'th-rename-tramp-buffer)
(defadvice find-file (around th-find-file activate)
 "Open FILENAME using tramp's sudo method if it's read-only."
 (if (and (file-root-p (ad-get-arg 0))
          (not (file-writable-p (ad-get-arg 0)))
          (y-or-n-p (concat "File "
                            (ad-get-arg 0)
                            " is read-only.  Open it as root? ")))
     (th-find-file-sudo (ad-get-arg 0))
   ad-do-it))
(defun th-find-file-sudo (file)
 "Opens FILE with root privileges."
 (interactive "F")
 (set-buffer (find-file (concat "/sudo::" file))))

参考

日本語が検索できない

(define-key isearch-mode-map "\C-k" 'isearch-edit-string) ; in searching
とすることでC-kを押して日本語編集できるようになる。
migemoをつかうのもよい。

eshell

tips

  • grep hoge {ls -1}

bookmark

  • つける・はずす: C-^
  • 前:C-;
  • 次:C-:

忘れそうなこと

Shell
M-x shell など
窓幅改行
M-x toggle-truncate-lines
変数truncate-partial-width-windowsにnil
Auto Fill
M-x auto-fill-mode
文字コード読み直し
C-x RET r
リージョンを強調表示
(transient-mark-mode t)
スクロールバーを消す
scroll-bar-mode でtoggle
設定ファイル内 (scroll-bar-mode -1)で無効
絶対行末改行
(setq truncate-partial-width-windows nil)
(setq truncate-lines nil)
画面を動かすスクロール
要求はカーソルを動かさずに上か下を見たいということ。どっちにあるかは分かっているという前提にたって、次のような関数を準備。
(defun line-to-top-of-window ()
 "Move the line point is on to top of window."
 (interactive)
 (recenter 0))
(defun line-to-bottom-of-window ()
 "Move the line point is on to bottom of window."
 (interactive)
 (recenter -1))
(global-set-key "\M-]" 'line-to-top-of-window)
(global-set-key "\M-[" 'line-to-bottom-of-window)
参考:http://www.bookshelf.jp/soft/meadow_31.html#SEC441
インデントのとりなおし
C-M-\ ・・・押しにくい
ソースの一部を隠したい
下記foldingを使う
定義済み変数のマークアップ
一行シェルコマンドの実行
M-!
pukiwikiもーど
http://www.bookshelf.jp/soft/meadow_54.html#SEC799
簡単install
install-elisp
install-elisp-from-emacswiki
C-n によって新しいラインを追加しない
(setq next-line-add-newlines nil)
コメントアウト(Comment Out)
C-c o
構文チェック(Validate command)
C-c C-v
ただしnsgmls(XML)が必要。
spell check
ispellコマンド
help参照
http://www.bookshelf.jp/soft/meadow_42.html#SEC629 を参考に。現在はこまっていないので導入はしない。
キーバインド
キーバインドする関数はinteractiveでなければいけない。
タブ/スペース切り替え
tabify, untabify
shellのコマンド
shell-command
redo
UndoしたあとにC-g(いまのなし!をおくる) C-_(UndoのUndoのいみ)
default-fontの設定
Emacs - changing default font size and font type?

Link集

要設定

起動時画面設定

.emacsで設定しようとすると、読み込み遅延がおこってうまくウィンドウ分割まで辿りつかない
(cf.http://www.fan.gr.jp/~ring/doc/elisp_19/elisp-jp_28.html#SEC387)

/.Xdefaults に次のように書けばよい。

Emacs.geometry: 40x32+30+0

でも、これはmacだと動かない(window system がXじゃないから当然)。したがって、フレーム生成を前にするか、ウィンドウ生成を後ろにするかして順番をうまくしないといけない。
http://www.dennougedougakkai-ndd.org/~delmonta/emacs/26.html

結局どうするか

起動時にフレームをもらってきて、そのフレームをいじくる。initialが反映されない、ということは逆にその時点でフレームが作成されていることを利用。

(progn (setq frame (next-frame))
           (set-frame-position frame 100 30)
           (set-frame-size frame 162 60)
           (setq w (frame-selected-window frame) )
           (split-window w 80 t)
)

2画面で横に4ページならべるととても楽しい

なお、フレームを広げるだけなら.emacsでよくて、こんなかんじ。

(setq initial-frame-alist (append '((top . 37)
         (left . 76)
         (height . 60)
         (width . 160)
         (scroll-bar-width . 3)) ;; scroll bar is removed!
initial-frame-alist))

起動時言語選択

TeXShopのせいでtexファイルはUTFではなくs-jisで書かなければいけないので、必ずs-jisを扱うようにしたい。
でもできない。

気持ちのいいスクロール

デフォルトのスクロールは移動量が多すぎるし、ポインタの位置の扱いが気に入らない

;; scroll config
(defun scroll-up-small ()
 "Small scroll up just 5 lines like other editors."
 (interactive)
 (scroll-up 5)
 (forward-line 5))
(defun scroll-down-small ()
 "Small scroll down just 5 lines like other editors."
 (interactive)
 (scroll-down 5)
 (forward-line -5));; `next-line' is not recommended.
(global-set-key "\C-v" 'scroll-up-small)
(global-set-key "\M-v" 'scroll-down-small)

folding.el

今いらない部分を隠す。
http://d.hatena.ne.jp/kajidai/20061023/1161641914
http://d.hatena.ne.jp/odz/20060913/1158203150

C-ffolding-fold-regionリージョン範囲を//{{{...//}}}で囲む
>folding-shift-in//{{...//}}}だけのブロックを表示
<folding-shift-out↑のshift-in modeから出る
C-tfolding-show-allあっscreenがじゃまして。。。
C-sfolding-show-current-entry
C-xfolding-hide-current-entry
C-ofolding-open-bufferネストしている//{{{もすべて開く
C-wfolding-whole-bufferすべての//{{{を閉じる
C-rfolding-convert-buffer-for-printingプリント用に//{{{..}}//をはずして表示
C-kfolding-marks-kill
C-vfolding-pick-move
vfolding-previous-visible-heading一つ前の"//{{{"へ飛ぶ
(space)folding-next-visible-headingつぎの"//{{{"へ飛ぶ
.folding-context-next-action
C-ufolding-toggle-enter-exitshift-inしたりshift-outしたり
C-qfolding-toggle-show-hide閉じたり開いたり
#folding-region-open-close選択範囲内の//{{{...を展開
;folding-comment-fold//{{{...//}}}ないの各行にコメントを挿入
%folding-convert-to-major-folds
/folding-alll-comment-blocks-in-region
C-yfolding-show-currnet-subtreeネストしてるすべての//{{{...//}}}を展開
C-zfolding-hide-current-subtreeネストしてるすべての//{{{...//}}}を閉じる
C-nfolding-display-name

PHP-flymakeにかんして

公式が落ちているので、データコピー
著作権に問題があったら消してください。

Syntax checking for PHP in Emacs
Posted on 12.19.14.1.10 6 Oc 3 Kayab by hosiawak

When programming PHP I often find it useful to see parse errors that are created as I type. A missing semicolon at the end of the line, a missing quotation mark, a dot in the wrong place, stuff like that that triggers PHP Fatal or Parse Errors. On-the-fly syntax checking is a common feature of good programming IDE’s and editors. Emacs is no exception – there’s flymake minor mode that is meant to help you discover errors at the time of writing code. Flymake is currently a part of Emacs distribution and it covers on-the-fly syntax checks for a lot of popular programming languages like C, C++, Java, Perl and others. Unfortunately PHP syntax checks are not included in that package. I have been looking around trying to find an extension for flymake to make it work with PHP but couldn’t find any so I decided to write my own.

Flymake-php.el is a bit os Lisp code that plays nicely with flymake and PHP on-the-fly syntax checking.

How to install ?

1. Copy the following code to your Emacs library path (for example ~/.emacs.d/flymake-php.el)

   ;; Flymake PHP Extension
   (require 'flymake)
   (defconst flymake-allowed-php-file-name-masks '(
                                                   (".php3'" flymake-php-init)
                                                   (".inc'" flymake-php-init)
                                                   (".php'" flymake-php-init))
     "Filename extensions that switch on flymake-php mode syntax checks")
   (defconst flymake-php-err-line-pattern-re '("(Parse|Fatal) error: (.*) in (.*) on line ([0-9]+)" 3 4 nil 2)
     "Regexp matching PHP error messages")
   (defun flymake-php-init ()
     (let* ((temp-file       (flymake-init-create-temp-buffer-copy
                              'flymake-create-temp-inplace))
            (local-file  (file-relative-name
                          temp-file
                          (file-name-directory buffer-file-name))))
       (list "php" (list "-f" local-file "-l"))))
   (defun flymake-php-load ()
     (setq flymake-allowed-file-name-masks (append flymake-allowed-file-name-masks flymake-allowed-php-file-name-masks))
     (setq flymake-err-line-patterns (cons flymake-php-err-line-pattern-re flymake-err-line-patterns))
     (flymake-mode t)
     (local-set-key "C-cd" 'flymake-display-err-menu-for-current-line))
   (provide 'flymake-php)

2. Make sure the library path is present in your .emacs, for example:

   (add-to-list 'load-path "~/.emacs.d/")

3. Require the flymake-php extension

(require 'flymake-php)

4. If you’re using php-mode (I bet you are if you program in PHP) you can add a hook to this extension, so that every time a php-mode is switched on you’ll have flymake minor mode running. 5.

(add-hook 'php-mode-user-hook 'flymake-php-load)

Usage

Now every time you open a php file that has an extension specified in flymake-allowed-php-file-name-masks a flymake minor mode will be switched on with on-the-fly syntax checking. If you see a highlighted line you can position the cursor on the line and press C-c d to see a popup window with an error message (similar to the screenshot above).

M-x flymake-goto-next-error and M-x flymake-goto-prev-error functions allow for easy navigation to the next/previous erroneous line, respectively. You can also bind these functions to the keys of your choice (local-set-key function).

How does this work ?

Quote from flymake-info manual:

Flymake runs the pre-configured syntax check tool (compiler for C++ files, `perl’ for perl files, etc.) in the background, passing it a temporary copy of the current buffer, and parses the output for known error/warning message patterns. Flymake then highlights erroneous lines (i.e. lines for which at least one error or warning has been reported by the syntax check tool), and displays an overall buffer status in the mode line. Status information displayed by Flymake contains total number of errors and warnings reported for the buffer during the last syntax check.

Syntax check is done ‘on-the-fly’. It is started whenever

- buffer is loaded - a newline character is added to the buffer - some changes were made to the buffer more than `0.5’ seconds ago (the delay is configurable).

Customise your flymake

You can further customise your flymake-mode. For example to disable a syntax check every time a newline is added to a buffer you can set flymake-start-syntax-check-on-newline variable to nil, eg.:

(setq flymake-start-syntax-check-on-newline nil)

You can also customise the look of the error line “face” (font, size and color of the error line) by setting flymake-errline-face. Please refer to flymake info manual for all the available options.
php.ini settings Because flymake will call php -l temp-buffer every time a request is trigger it’s a good idea to disable error logging in php.ini (cli version)
; Log errors into a log file (server-specific log, stderr, or error_log (below)) ; As stated above, you’re strongly advised to use error logging in place of ; error displaying on production web sites. log_errors = Off

What about warnings ?

If you’re an adventurous soul (by this I mean “hacking Lisp code” type of adventure :) ), you may extend this a little bit and add support for PHP warning messages.