Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mode-local variables in Emacs

Tags:

emacs

elisp

I would like to have a global keyboard shortcut that shows the value of a variable. However, the variable's value could change according to the current major mode in the current buffer.

I tried to add the following to my ~/.emacs:

(defun my-elisp-mode-setup ()
  (defvar-local *current-mode-var* "elisp-mode")
)
(defun my-sh-mode-setup ()
  (defvar-local *current-mode-var* "sh-mode")
)
(add-hook 'emacs-lisp-mode-hook 'my-elisp-mode-setup)
(add-hook 'sh-mode-hook 'my-sh-mode-setup)

If I now start Emacs with emacs test.sh and then type M-x describe-variable *current-mode-var* in the test.sh buffer, I get

*current-mode-var*'s value is "elisp-mode"

  Automatically becomes buffer-local when set.

Documentation:
Not documented as a variable.

while I expected to get *current-mode-var*'s value is "sh-mode"

like image 969
Håkon Hægland Avatar asked Jan 11 '23 13:01

Håkon Hægland


2 Answers

The variables are evaled only at first declaration. All further declarations are skipped. You need a setq instead.

like image 102
abo-abo Avatar answered Jan 19 '23 00:01

abo-abo


If all you want to do is examine a variable to determine the major mode (which it seems is what you are doing), then just examine variable major-mode. That's what it's for.

And if you want a key/command to do that, then just create one:

(defun which-mode ()
  "Echo the current major mode in the echo area."
  (interactive)
  (message "Major mode: %s" major-mode))

Or use variable mode-name if you prefer a human-friendly major-mode name.

like image 23
Drew Avatar answered Jan 19 '23 00:01

Drew