Is there reliable way to temporarily switch the current buffer to another major mode, perform some function, then switch back to the original mode?

Basically, I was looking for something similar to with-current-buffer below, but instead of temporarily switching to a different buffer, switch to a different major mode during an action.

Macro: with-current-buffer buffer body...

The with-current-buffer macro saves the identity of the current buffer, makes buffer current, evaluates the body forms, and finally restores the buffer. The return value is the value of the last form in body. The current buffer is restored even in case of an abnormal exit via throw or error

I tried something here (for reasons also explained there) along the lines of:

  (let ((current-mode major-mode))
    (funcall current-mode)

to switch to the text-mode first, perform the action, and then switch back. This works as expected only if the action is completed. However, if the action in the middle is canceled or there is an error, the last step for restoring mode is skipped and the current buffer is stuck in the text-mode.

Is there a safe way to do, e.g. (with-current-mode "text-mode" (...))?


1 Answer 1


See C-hig (elisp)Cleanups for how to use unwind-protect

The ‘unwind-protect’ construct is essential whenever you temporarily put a data structure in an inconsistent state; it permits you to make the data consistent again in the event of an error or throw.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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