1. (defvar prev-window (selected-window)
  2.   "Holds the previous window which was selected before a switch
  3.  using other-window-repeat.")
  4.  
  5. ;; a better command to be bound to C-x o
  6. (defun other-window-repeat (COUNT &optional no-repeat)
  7.   "Calls other-window.  If a multiple key sequence was used to
  8.  call this then the last key can be used on its own to repeat
  9.  this, like kmacro-call-macro."
  10.   (interactive "p")
  11.   (let ((repeat-key (and (null no-repeat)
  12.                          (> (length (this-single-command-keys)) 1)
  13.                          last-input-event))
  14.         repeat-key-str
  15.         (nxt t))
  16.     ;; save current window
  17.     (setq prev-window (selected-window))
  18.     (other-window COUNT)
  19.     (when repeat-key
  20.       (setq repeat-key-str (format-kbd-macro (vector repeat-key) nil)))
  21.     (while repeat-key
  22.       (unless (current-message)
  23.         (message "(Type %s to keep cycling)"
  24.                  repeat-key-str))
  25.       (if (equal repeat-key (read-event))
  26.           (progn
  27.             (clear-this-command-keys t)
  28.             (other-window COUNT)
  29.             ;; if we cycle all the way to the same window, set prev-window to
  30.             ;; next window, then if we continue to cycle set it back again
  31.             (when (eq prev-window (selected-window))
  32.               (setq prev-window (if nxt
  33.                                     (next-window)
  34.                                   (previous-window)))
  35.               (setq nxt (not nxt)))
  36.             (setq last-input-event nil))
  37.         (setq repeat-key nil)))
  38.     (when last-input-event
  39.       (clear-this-command-keys t)
  40.       (setq unread-command-events (list last-input-event)))))
  41. (global-set-key (kbd "C-x o") 'other-window-repeat)
  42.  
  43. (defun switch-prev-window ()
  44.   "Switchs back to previous window that was selected before last
  45. call to other-window-repeat or switch-prev-window."
  46.   (interactive)
  47.   (when (or (eq prev-window (selected-window))
  48.             (not (window-live-p prev-window)))
  49.     ;; previous window is best guess
  50.     (setq prev-window (previous-window)))
  51.   (let ((wind prev-window))
  52.     (setq prev-window (selected-window))
  53.     (select-window wind)))
  54. (global-set-key (kbd "M-'") 'switch-prev-window)