Skip to content

Instantly share code, notes, and snippets.

@buzztaiki
Created February 11, 2024 10:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save buzztaiki/433ce4d1e70ad4851c42349d87845ea2 to your computer and use it in GitHub Desktop.
Save buzztaiki/433ce4d1e70ad4851c42349d87845ea2 to your computer and use it in GitHub Desktop.
Emacsで誰が変数を変更したか調べる

Emacsで誰が変数を変更したか調べる

色々パッケージ入れてると、なぜか変数がよく分からない値になってる事がたまにある。そんな時は debug-on-variable-changeadd-variable-watcher を使うと調べる事ができる。

Info から引用:

https://ayatakesi.github.io/lispref/29.2/elisp-ja.html#Variable-Debugging

Command: debug-on-variable-change variable

この関数はvariableの変更時に常にデバッガが呼び出されるようにアレンジする。

https://ayatakesi.github.io/lispref/29.2/elisp-ja.html#Watching-Variables

Function: add-variable-watcher symbol watch-function

この関数はsymbolが変化したときは常にwatch-functionが呼び出されるようにアレンジする。エイリアスを介した変更にも同じ効果をもつ(変数のエイリアスを参照)。

条件無しでいいなら debug-on-variable-change が手軽。何か条件を付けたいなら add-variable-watcher がよさげ。

add-variable-watcher の例はこんな感じ:

(defun variable-watcher (symbol newval operation where)
  (when (and (string= (buffer-name where) "main.go") (= newval 2))
    (backtrace)
    (message "variable event: %s" (list symbol newval operation where))
    (backtrace)))

;; 登録
(add-variable-watcher 'tab-width 'variable-watcher)
;; 解除
(remove-variable-watcher 'tab-width 'variable-watcher)

どちらも Emacs 26 で導入されたものらしい。知らなかった。

https://github.com/emacs-mirror/emacs/blob/30b4d902326546ca2b383d56caadbe0adaf0fe89/etc/NEWS.26#L1628-L1630

New function 'add-variable-watcher' can be used to call a function

when a symbol's value is changed. This is used to implement the new debugger command 'debug-on-variable-change'.

ちなみに僕の場合は editorconfig が変えていたのでした。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment