Search code examples
emacsbufferelispmode

Programmatically setting major mode of buffer with emacs lisp


I wish to programmatically set the major mode of a buffer. I have dug into the documentation, and the function set-buffer-major-mode only takes a buffer object. I am essentially looking for a function that takes a buffer object and a mode name.

Alternatively, I also tried using auto-mode-alist by forcing the buffer to have a file extension but that did not work even when I called the set-buffer-major-mode function.

Thanks for all the help!


Solution

  • The basics are that if you want to switch to my mode, all you have to do is to call my-mode, for example:

    (with-current-buffer buffer
      (my-mode))
    

    If you have a buffer and a variable bound to the major mode, you could use the following:

    (with-current-buffer buffer
      (funcall the-mode-i-want))
    

    Again, if you have a variable bound to a string, you have to convert it to a symbol using intern:

    (with-current-buffer buffer
      (funcall (intern the-name-of-the-mode-i-want)))