6

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 ()
  (interactive)
  (jump-to-n-th-bookmark 0))

(defun jump-to-2nd-bookmark ()
  (interactive)
  (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))
Drew
  • 75,699
  • 9
  • 109
  • 225
user4035
  • 1,039
  • 11
  • 24

2 Answers2

7

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).

Kaushal Modi
  • 25,203
  • 3
  • 74
  • 179
sds
  • 5,928
  • 20
  • 39
3

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.

Kaushal Modi
  • 25,203
  • 3
  • 74
  • 179
Lindydancer
  • 6,095
  • 1
  • 13
  • 25