【问题标题】:Mode-local variables in EmacsEmacs 中的模式局部变量
【发布时间】:2014-01-05 19:12:52
【问题描述】:

我想要一个显示变量值的全局键盘快捷键。但是,变量的值可能会根据当前缓冲区中的当前主模式而改变。

我尝试将以下内容添加到我的~/.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)

如果我现在用emacs test.sh 启动Emacs,然后在test.sh 缓冲区中输入M-x describe-variable *current-mode-var*,我会得到

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

  Automatically becomes buffer-local when set.

Documentation:
Not documented as a variable.

虽然我希望得到*current-mode-var*'s value is "sh-mode"

【问题讨论】:

    标签: emacs elisp


    【解决方案1】:

    变量仅在第一次声明时被评估。跳过所有进一步的声明。 你需要一个setq

    【讨论】:

    • 谢谢!如果我使用setq,那么变量如何成为本地变量?
    • 声明后是本地缓冲区。这类似于在 C 中声明类型和赋值:赋值不会改变类型。所以defvar-local 后跟setq不会将变量更改为非本地。
    • Ok.. 这是否意味着您必须在~/.emacs 中添加(defvar-local *current-mode-var* nil),然后在模式挂钩中使用setq
    • 是的,应该可以。或者在每种模式下声明,在每种模式下设置q。声明东西没有坏处。
    • 在 emacs 24 中你可以使用setq-local
    【解决方案2】:

    如果您只想检查一个变量以确定主要模式(看起来就是您正在做的),那么只需检查变量major-mode。这就是它的用途。

    如果你想要一个键/命令来做到这一点,那么只需创建一个:

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

    如果您更喜欢人性化的主模式名称,请使用变量 mode-name

    【讨论】:

      【解决方案3】:

      我更喜欢官方原生包https://www.emacswiki.org/emacs/ModeLocal。 它的可配置性更好,因为您不需要add-hook

      例如

      (require 'mode-local)
      (setq-mode-local sh-mode *current-mode-var* "sh-mode")
      (setq-mode-local emacs-lisp-mode *current-mode-var* "elisp-mode")
      

      然后通过改变模式来改变*current-mode-var*的值

      【讨论】:

        【解决方案4】:

        defvar-local 是一个在底层调用 defvarmake-variable-buffer-local 的宏。

        defvar SYMBOL [VALUE [DOC-STRING]

        ...但是如果 SYMBOL 不是 void,VALUE 不会被计算,并且 SYMBOL 的值保持不变...

        你的代码应该是:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多