I'm trying to create a shortcut (C-c c) regardless of what kind of file is currently opened (it could be a .pl file or a .txt file or an extension less file) pressing C-c c should turn on org mode if its not turned on already. pressing it again and again toggles it off and on....

Here's what I have

(global-set-key (kbd "C-c c") (lambda () (interactive)

Any help? It's important that when turning off org mode, whatever the "native" mode the file was originally on comes back on.

  • The canonical "toggle" in Elisp is called a minor mode, so you can use define-minor-mode for that. – Stefan Oct 8 '19 at 22:42

This seems to work on a few examples I have tried:

(defvar-local last-mode nil
  "Buffer-local variable to store last mode in.")

(defun toggle-org-mode ()
  "Toggle the mode between the current mode and `org-mode'."
  (make-local-variable 'last-mode)
  (put 'last-mode 'permanent-local t)
  (if (eq major-mode 'org-mode)
        (message "switch back to %s" last-mode)
        (funcall last-mode)
        (setq last-mode nil))
    ;; This means you are in the native mode you started in and now want to
    ;; switch to org-mode
    (message "switch to org from %s" major-mode)
    (setq last-mode major-mode)

This is more subtle than it seemed. You have to mark the buffer-local variable as permanent, or it can get wiped out by changing the major mode.

| improve this answer | |
  • ahh my neighbor from ucla! – american-ninja-warrior Oct 8 '19 at 0:58
  • 1
    This does not work: what happens if I have two buffers (different major modes), call the function in the first buffer, call it in the second buffer and then call it again in the first buffer? Maybe making last-mode buffer-local might work. – NickD Oct 8 '19 at 4:18
  • that is a good catch. I have modified the solution to make last-mode buffer local. – John Kitchin Oct 8 '19 at 10:59
  • I had to comment out the defvar statements, otherwise I got 'Symbol’s function definition is void: nil' when reverting. I believe the value of last-mode is nil – american-ninja-warrior Oct 8 '19 at 12:56
  • see the new edit. It is trickier than I thought to use local variables. – John Kitchin Oct 8 '19 at 20:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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