KDOC 732: Emacsの負の前置引数は-1を渡すだけで、逆向きに動くかはコマンドが決める
この文書のステータス
- 作成
- <署名>
- レビュー
- <署名>
概要
Emacs に負の前置引数という概念がある。たとえば C-- C-f と打つと、 C-f を反転させて1文字前へ戻る。
これがどういう仕組みなのか気になった。すべてのコマンドに逆向きの動きが定義されているとは思えない。
C–はシンボルの-を渡す
C-- C-f で何が起きているかを順に見ていく。
C-- には、 M-- と同じ negative-argument が割り当てられている。
(list (key-binding (kbd "C--")) (key-binding (kbd "M--")))
(negative-argument negative-argument)
Emacs Lisp マニュアルによると、 M-- が渡すのはシンボル - で、数値として読むと -1 になる。
etc=$(emacs -Q --batch --eval '(princ data-directory)')
info -f "$etc/../../../info/elisp.info.gz" -n 'Prefix Command Arguments' -o - | sed -n '30,33p'
• The symbol ‘-’. This indicates that ‘M--’ or ‘C-u -’ was typed,
without following digits. The equivalent numeric value is −1, but
some commands make a distinction between the integer −1 and the
symbol ‘-’.
受け取り方はinteractiveの指定で決まる
前置引数をどの形で受け取るかは、コマンドごとに interactive のフォーマットで決まる。指定には1文字のコードを書く。 p と書くと前置引数を数値に直して受け取る。 - は -1 になる。
etc=$(emacs -Q --batch --eval '(princ data-directory)')
info -f "$etc/../../../info/elisp.info.gz" -n 'Interactive Codes' -o - | sed -n '172,174p'
‘p’
The numeric prefix argument. (Note that this ‘p’ is lower case.)
No I/O.
forward-charは-1を足して戻る
C-f に割り当てられている forward-char の指定を見る。
(interactive-form 'forward-char)
(interactive "^p")
p を使っている1。そのため C-- のあとに C-f を押すと、 forward-char は -1 を受け取る。
forward-char は受け取った n をそのまま move_point に渡し、第2引数には前向きを表す 1 を渡す。
https://github.com/emacs-mirror/emacs/blob/a360712c9d272d950d8d8255ef74570f7e90b7d9/src/cmds.c#L78-L81
(Lisp_Object n)
{
return move_point (n, 1);
}
move_point は第2引数が前向きなら、今の位置に n をそのまま足す。-1 を足すので1文字前へ戻る。
https://github.com/emacs-mirror/emacs/blob/a360712c9d272d950d8d8255ef74570f7e90b7d9/src/cmds.c#L52
new_point = PT + (forward ? XFIXNUM (n) : - XFIXNUM (n));
逆向きにできるのは一部のコマンドだけ
以上で見たように、 forward-char は引数を位置にそのまま足すので、逆の操作を定義せずに逆向きを表現できる。引数をこのように計算に使うコマンドなら、同じように逆向きを表現できるだろう。しかし、そういう種類の操作は限られているように見える。
Emacs マニュアルには、負の引数で逆向きに動くのは、引数を繰り返し回数として読む一部のコマンドだけだと書かれている。
etc=$(emacs -Q --batch --eval '(princ data-directory)')
info -f "$etc/../../../info/emacs.info.gz" -n 'Arguments' -o - | sed -n '8,13p'
“numeric argument” (also called a “prefix argument”). Some commands
interpret the argument as a repetition count. For example, giving ‘C-f’
an argument of ten causes it to move point forward by ten characters
instead of one. With these commands, no argument is equivalent to an
argument of one, and negative arguments cause them to move or act in the
opposite direction.
関連
抽象。
- 引数の符号を足し算にそのまま流すと、逆の操作を別に書かなくて済む
関連。
- 前提: KDOC 703: Emacs Lispのinteractiveの指定は対話的に呼んだときだけ引数を埋める。
"p"で前置引数が数値になるのは、このinteractiveの仕組みによる
Footnotes:
"^p" の ^ は別の機能のための印で、Shift を押しながら C-f を打つと範囲選択できるようにしている。