Search code examples
emacselisp

Switch back and forth between last two buffers in emacs


I would like to switch back and forth between the last two visited buffers (current one and previous one) and bind the command to M-b.

(switch-to-buffer (other-buffer)) in theory should accomplish this, but adding the following code to my .emacs has no effect.

(defun my-switch-to-other-buffer ()
  "Switch to other buffer"
  (interactive)
  (switch-to-buffer (other-buffer)))

(global-set-key [M-b] 'my-switch-to-other-buffer)

Please suggest a fix to the code above or a better way to accomplish this task.


Solution

  • Your code looks pretty well and seems to work in my emacs session.

    Are you sure about the [M-b] syntax?

    If this is the problem you probably want to use the kbd function instead to determinie the right way to spell the key combination.

    (global-set-key (kbd "M-b") 'my-switch-to-other-buffer)
    

    I always define my keybindings this way as I tend to forget how to correctly ?\C-#whatever get the name right.

    Using kbd it's extremely simple, as it accepts a string having the same syntax as that echoed by decribe-key usually bound to C-h C-k.

    This way I just have to type C-h C-k in case I don't know how the key is labeled and put the output of this command in my call to kbd. Especially in cases where it doesn't seem to obvious how to get it right kbd is extremely helpful it even works with more complex names (kbd "<backtab>") and the like.