想给变量添加docstring是否只能用defvar?

setq似乎不能添加docstring,defvar一般推荐写法又是(defvar *var*)各位一般是怎么给变量添加docstring的呢

defvar定义变量。用defcustom定义可供customize修改的变量。

你在哪儿看到的?

抱歉发现star被吞了…说是(defvar *var*)这个样子的…

理论上是可以的

Symbol Properties

Standard Properties

variable-documentation

If non- nil , this specifies the named variable’s documentation string. This is set automatically by defvar and related functions. See Defining Faces.

所以理论上这样可以给变量添加文档。不过我自己试的时候没成功……describe-variable不显示添加的变量。

(put var 'variable-documentation "My variable")

我知道Common Lisp有用星号的写法,但是Emacs Lisp里面用的不多。估计是因为Emacs Lisp不久之前还只支持dynamic binding。

(setq zxc 89)
(put 'zxc 'variable-documentation "My variable: zxc")
(describe-variable 'zxc)
1 个赞

谢谢,我自己试了下是可以正常添加的,应该是@zhouchongzxc 的写法 (put 'var 'variable-documentation "My variable")

put的第一个参数应该是symbol……

(setq remx 'booooool)
(put remx 'variable-documentation "AAAA")
(describe-variable 'remx) ;; => Not documented as a variable.
(describe-variable 'booooool) ;; => AAAA

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(setq remx 'booooool)
(put 'remx 'variable-documentation "AAAA")
(describe-variable 'remx) ;; => AAAA
(describe-variable 'booooool) ;; => Not documented as a variable.

话说回来,这操作其实还挺有用的啊……比如我这种强迫症患者想给package里的variable添加doctoring的时候……

我说呢,六个字

你只需要记住: setq是给变量赋值, defvar是定义变量, 就OK了, 一个变量该如何使用,当然是定义这个变量时就应该确定的

话说为啥Emacs并不阻止用setq定义变量……

为了在写配置的时候,少写一句话。。。。。我猜测是这样子。

defvar也可以不写docstring啊