Emacs: Cycling through workspaces in perspective mode


About two days ago, one of my coworkers who started using emacs around the same time as I did and who comes from a similar vim setup as mine, introduced me to perspective.el.

From the docs:

perspective.el provides multiple workspaces (or "perspectives") for each Emacs frame. This makes it easy to work on many separate projects without getting lost in all the buffers.

Since I inmediatly found it so convenient I wanted to make it faster to switch between perspectives by setting up a keybinding for it. Sadly, the provided way to do it was to use the persp-next function which has the drawback of prompting for a name when you've reached the last perspective. So I went and checked how persp-next works and found this, which is pretty straightforward:

(defun persp-next ()
  "Switch to next perspective (to the right)."
  (interactive)
  (persp-switch (nth (1+ (persp-curr-position))
                     (persp-all-names))))

It showed me that a) (persp-all-names) returns the list of all the available perspectives and b) I can call persp-switch with the name of the perspective I want to go to as an argument. With that in mind, I wrote this little function that makes perspective cycling behave the way I want.

(defun persp-cycle ()
  "Cycle throught the available perspectives."
  (interactive)
  (let ((next-pos (1+ (persp-curr-position)))
        (list-size (length (persp-all-names))))
  (cond ((eq 1 list-size) (persp-switch nil))
         ((>= next-pos list-size) (persp-switch (nth 0 (persp-all-names))))
         (t (persp-next)))))

When there are no other perspectives besides the current one, it'll prompt you for a name. Else, it'll just jump to the next perspective and go back to the first one after reaching the end of the list.