无法以编程方式将键分配给循环中的书签

Can't assign keys programmatically to bookmarks in a loop

假设,列表中有 n 个书签 (n <= 9)

% Bookmark
- --------
1  mark-1                     ~/work/file-1.txt
2  mark-2                     ~/work/file-2.txt
  ...
9  mark-9                     ~/work/file-9.txt

我想以编程方式附加键 <n> 以跳转到第 n 个书签。

代码

;get a sorted list of bookmarks
(let ((bookmarks (sort (bookmark-all-names) 'string<))
      (i 1))
  (while bookmarks
    (setq key (number-to-string i))
    ;try to assign key i -> jump-to-bookmark(bookmarks[i])
    (define-key bookmark-bmenu-mode-map
      (kbd key)
      (lambda () (interactive) (bookmark-jump (car bookmarks))))
    ;next bookmark
    (setq bookmarks (cdr bookmarks))
    (setq i (+ i 1))
              ))

不幸的是,它给出了一个错误:

(wrong-type-argument integer-or-marker-p key)

这里的问题与以下事实有关:您正在使用动态绑定,但试图从 lambda 访问不再在范围内的变量(书签)。您可以通过这样定义 lambda 来修复它:

`(lambda () (interactive) (bookmark-jump (car ',bookmarks))))

可以看到一个解释here

(顺便说一句,当您的书签超过 9 个时,代码将失败)

这是修改后的代码,对我来说效果很好:

(let ((bookmarks (sort (bookmark-all-names) 'string<))
      (i 1)
      key)
  (while bookmarks
    (setq key (number-to-string i))
    (define-key bookmark-bmenu-mode-map
      (kbd key)
      `(lambda () (interactive) (bookmark-jump (car ',bookmarks))))
    (setq bookmarks (cdr bookmarks))
    (setq i (+ i 1))))