Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a buffer-local key binding in Emacs?

I've been working on an Emacs minor mode lately and part of its functionality was displaying images in separate buffers. So far I've been using a function like this:

(defun create-buffer-with-image (name)
  (let ((buffer (generate-new-buffer name))
        (image (get-svg-for-kanji-code name)))
    (switch-to-buffer buffer)
    (turn-on-iimage-mode)
    (iimage-mode-buffer t)
    (insert-image image)))

and it produces a buffer with the image passed as argument, but closing the buffer requires hitting C-x k and Return, which started to get cumbersome after a while. The way to simplify closing of such transient buffers would be to have a key binding for the kill-this-buffer function, but it would need to be buffer-specific, so as not to mess up anything else. The question is how to make such a binding with the creation of a buffer.

like image 339
Wojciech Gac Avatar asked Dec 05 '14 17:12

Wojciech Gac


2 Answers

From EmacsWiki: https://www.emacswiki.org/emacs/BufferLocalKeys

For buffer-local keys, you cannot use local-set-key, unless you want to modify the keymap of the entire major-mode in question: local-set-key is local to a major-mode, not to a buffer.

For buffer-local modifications, use this instead:

(use-local-map (copy-keymap foo-mode-map))
(local-set-key "d" 'some-function)

Written by:  TiagoSaboga


To inspect the change, type C-h b aka M-x describe-bindings

like image 112
lawlist Avatar answered Sep 22 '22 16:09

lawlist


I'd suggest you add a call to special-mode after the call to switch-to-buffer. In the longer run, you'll want to use your own major mode, so you'd do:

(define-derived-mode my-image-mode special-mode "MyImage"
  "My own major mode to display images."
  ;; We could add more things here
  )

(defun create-buffer-with-image (name)
  (with-current-buffer (generate-new-buffer name)
    (my-image-mode)
    (let ((image (get-svg-for-kanji-code name)))
      (turn-on-iimage-mode)
      (iimage-mode-buffer t)
      (insert-image image)
      (pop-to-bffer (current-buffer)))))
like image 40
Stefan Avatar answered Sep 22 '22 16:09

Stefan