102

I have a question about Emacs Lisp. What is the difference between setq and setq-default?

Tutorials say setq takes effect in the local buffer while setq-default affects all buffers.

For example, if I wrote (setq a-var a-vars-value) in init.el, I found after starting Emacs and opening a new buffer, the a-var is also there and its value is a-vars-value. I thought it was not supposed to be there. It seems there is no difference between setq and setq-default.

Is there something wrong with my understanding?

For example:

  1. I wrote (setq hello 123) in the init.el file, and I run emacs abuffer in the shell, then I input "hello C-x C-e", it shows "123". The same happens when I run this in all new buffers.

  2. I wrote (setq tab-width 4) in the init.el file. When I run tab-width C-x C-e, it shows "8" (Current mode is 'Text'). However, when I use (setq-default tab-width 4), it show "4". I can't explain this phenomenon.

4

1 回答 1

118

Emacs 中的一些变量是“本地缓冲区”,这意味着每个缓冲区都可以有一个单独的值来覆盖全局默认值。tab-width是缓冲区局部变量的一个很好的例子。

如果变量是缓冲区本地的,则setq在当前缓冲区中设置其本地值并setq-default设置全局默认值。

如果一个变量不是缓冲区局部的,那么setqsetq-default做同样的事情。

在您的情况 2 中,(setq tab-width 4)将当前缓冲区中的缓冲区局部值设置tab-width为 4,将全局默认值tab-width仍然保留为 8,因此当您tab-width在没有局部值的不同缓冲区中进行评估时,您会看到 8。然后,当您将默认值设置为 4 时,该缓冲区会拾取它,因为它仍然没有本地值。

于 2013-08-11T15:43:58.037 回答