This code opens 1-st & 2-nd bookmarks when 1 & 2 keys are pressed on bookmarks page:

(defun jump-to-n-th-bookmark (n)
  (let ((bookmarks (sort (bookmark-all-names) 'string<)))
    (bookmark-jump (nth n bookmarks))

(defun jump-to-1th-bookmark ()
  (jump-to-n-th-bookmark 0))

(defun jump-to-2nd-bookmark ()
  (jump-to-n-th-bookmark 1))

(defun my-bookmark-mode ()
  (define-key bookmark-bmenu-mode-map (kbd "1") 'jump-to-1th-bookmark)
  (define-key bookmark-bmenu-mode-map (kbd "2") 'jump-to-2nd-bookmark))

(add-hook 'bookmark-bmenu-mode-hook 'my-bookmark-mode)

Can we get rid of jump-to-1th-bookmark and jump-to-2nd-bookmark functions and have something like this:

(defun my-bookmark-mode ()
  ;pass a parameter together with function
  (define-key bookmark-bmenu-mode-map (kbd "1") 'jump-to-n-th-bookmark 0)
  (define-key bookmark-bmenu-mode-map (kbd "2") 'jump-to-n-th-bookmark 1))

Not out of the box.

However, we can use lambda:

(define-key my-map my-key (lambda () (interactive) (jump... ...)))

You can even create a macro:

(defmacro defkey-arg (map key func &rest args)
 `(define-key ,map ,key (lambda () (interactive) (,func ,@args))))

(defkey-arg bookmark-bmenu-mode-map (kbd "1") jump-to-n-th-bookmark 0)

EDIT: in your specific case it makes much more sense to make jump-to-n-th-bookmark interactive:

(defun jump-to-n-th-bookmark (n)
  (intractive "p")
  (let ((bookmarks (sort (bookmark-all-names) 'string<)))
    (bookmark-jump (nth n bookmarks))))
(define-key bookmark-bmenu-mode-map (kbd "j") 'jump-to-n-th-bookmark)

now you can jump to 3rd bookmark using 3 j (assuming that the bookmark-bmenu-mode is derived from special-mode which binds digits to digit-argument).


One approach is to check the last keyboard event, this way you can bind the same command to all numeric keys.

(defun jump-to-n-th-bookmark (n)
  (interactive (list (- last-command-event ?0)))
  (let ((bookmarks (sort (bookmark-all-names) 'string<)))
  (bookmark-jump (nth n bookmarks))))

(defun my-bookmark-mode ()
  (define-key bookmark-bmenu-mode-map (kbd "1") 'jump-to-n-th-bookmark)
  (define-key bookmark-bmenu-mode-map (kbd "2") 'jump-to-n-th-bookmark))

You can still call jump-to-n-th-bookmark with an explicit number, but when called interactively, it expects it be bound to a key sequence ending in a number key.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.