Just as the question stated, I would like a function that would count of the windows that are currently being shown in that frame.

So this:

|              |             |
|              |             |
|  *scratch*   | *Messages*  |
|              |             |
|              |             |
|              |             |
|           *Help*           |
|                            |

Would return => 3

I started a function below:

(defun count-windows ()
  "Count how many buffers are currently being shown."
  • 2
    Do you mean the number of windows, or the number of unique buffers visible in windows? – Dan Nov 13 '14 at 13:26
  • 3
    In the example given, you have 3 windows showing 3 different buffers. If, say, 2 of those windows were showing *scratch*, would you want the function to return 3 or 2? – Dan Nov 13 '14 at 13:42
  • @Dan, sorry for the misunderstanding, and I would the function to return 3 still. – Luke Shimkus Nov 13 '14 at 13:44
  • 1
    Got it -- answer below gives both options: it looks like you want the simpler one (count-windows). – Dan Nov 13 '14 at 13:50

If you mean the number of windows regardless of which buffers are showing, then: (length (window-list)) will do it. Better still, you can just use the existing (count-windows) function.

If you want to count the number of unique buffers visible in windows on the frame, then you can use:

(length (cl-delete-duplicates (mapcar #'window-buffer (window-list))))

(Note that window-list can also take an optional FRAME argument if you want something other than the selected frame.)

Wrapping the latter in your function call will give you:

(defun count-unique-visible-buffers (&optional frame)
  "Count how many buffers are currently being shown.  Defaults to
selected frame."
  (length (cl-delete-duplicates (mapcar #'window-buffer (window-list frame)))))

(Note that this function assumes you have loaded 'cl-lib. As per comments, you could use delete-dups in place of cl-delete-duplicates if you want to avoid cl-lib.)

  • 2
    +1 Great answer! The only info that's missing is that cl-delete-duplicates needs to be made available by requireing cl. – itsjeyd Nov 13 '14 at 13:43
  • 1
    Good catch, thanks. I've edited the answer to mention it. – Dan Nov 13 '14 at 13:47
  • 1
    Do you know a way or a function that doesn't require you to load 'cl-lib? – Luke Shimkus Nov 13 '14 at 13:54
  • 3
    Actually, yes: it turns out the delete-dups would also work, and doesn't require 'cl-lib. – Dan Nov 13 '14 at 13:57

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.