Emacs中的模式局部变量

时间:2014-01-05 19:12:52

标签: emacs elisp

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

我尝试将以下内容添加到~/.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,然后在M-x describe-variable *current-mode-var*缓冲区中输入test.sh,我就会

*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"

4 个答案:

答案 0 :(得分:4)

变量仅在第一次声明时被证实。所有进一步的声明都被跳过。 您需要setq代替。

答案 1 :(得分:2)

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

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

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

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

答案 2 :(得分:2)

我更喜欢官方原生包https://www.emacswiki.org/emacs/ModeLocal。 它可以更好地配置,因为您不需要import akka.stream.scaladsl.Framing import scala.util.{Success, Try} import akka.util.ByteString import play.api.libs.json.{JsSuccess, Json, Reads} import play.api.libs.oauth.{ConsumerKey, OAuthCalculator, RequestToken} case class Tweet(id: Long, text: String) object Tweet { implicit val reads: Reads[Tweet] = Json.reads[Tweet] } def twitter = Action.async { implicit request => ws.url("https://stream.twitter.com/1.1/statuses/filter.json?track=Rio2016") .sign(OAuthCalculator(consumerKey, requestToken)) .withMethod("POST") .stream().flatMap { response => response.body // Split up the byte stream into delimited chunks. Note // that the chunks are quite big .via(Framing.delimiter(ByteString.fromString("\n"), 20000)) // Parse the chunks into JSON, and then to a Tweet. // A better parsing strategy would be to account for all // the different possible responses, but here we just // collect those that match a Tweet. .map(bytes => Try(Json.parse(bytes.toArray).validate[Tweet])) .collect { case Success(JsSuccess(tweet, _)) => tweet.text } // Print out each chunk .runForeach(println).map { _ => Ok("done") } } }

例如

Materializer

然后只需更改模式导致更改add-hook

的值

答案 3 :(得分:0)

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

<块引用>

defvar 符号 [VALUE [DOC-STRING]

...但如果 SYMBOL 不为空,则不评估 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)