Emacs Lisp中的动态变量

时间:2013-12-12 10:59:34

标签: emacs elisp

我的代码看起来像这样

(defun work ()
  (interactive)
  (case major-mode
    ('javascript-mode (setq js-indent-level (if (eq js-indent-level 2) 4 2)))
    ('css-mode (setq cssm-indent-level (if (eq cssm-indent-level 2) 4 2)))
    ('nxml-mode (setq nxml-child-indent (if (eq nxml-child-indent 2) 4 2)))
    (t (setq c-basic-offset (if (eq c-basic-offset 2) 4 2)))))

在缩进级别2和4之间切换(我使用4个缩进空格,但需要2个工作),是否可以缩小代码,每行看起来像是这样的代码:

(defun work ()
  (interactive)
  (let ((var (case major-mode
                 ('javascript-mode 'js-indent-level)
                 ('css-mode 'cssm-indent-level)
                 ('nxml-mode 'nxml-child-indent)
                 (t 'c-basic-offset))))
     ;; like C pointers
     (setf (pointer var) (if (eq (pointer var) 2) 4 2))))

(defun work ()
  (interactive)
  (let ((var (cdr (assoc major-mode indent-vars))))
     (setf (pointer var) (if (eq (pointer var) 2) 4 2))))

如果我在indent-vars alist中有我的缩进变量

我需要使用宏还是eval呢?

2 个答案:

答案 0 :(得分:3)

您需要symbol-valueset

(defun work ()
  (interactive)
  (let ((var (cdr (assoc major-mode indent-vars))))
     (set var (if (eq (symbol-value var) 2) 4 2))))

答案 1 :(得分:2)

您可以尝试以下操作,而不是setf - 构建。

(set var (if (eq (eval var) 2) 4 2))

它应该可以工作,但我没有测试它。