Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Two ways of messing with spaces
#include <unistd.h>
#include <CoreServices/CoreServices.h>
#include <ApplicationServices/ApplicationServices.h>
typedef int CGSConnection;
extern OSStatus CGSGetWorkspace(const CGSConnection cid, int *workspace);
extern OSStatus CGSSetWorkspace(const CGSConnection cid, int workspace);
extern CGSConnection _CGSDefaultConnection(void);
int get_space_id(void);
void set_space_by_index(int space);
int get_space_id(void)
int space;
CFArrayRef windows = CGWindowListCopyWindowInfo( kCGWindowListOptionOnScreenOnly, kCGNullWindowID );
CFIndex i, n;
for (i = 0, n = CFArrayGetCount(windows); i < n; i++) {
CFDictionaryRef windict = CFArrayGetValueAtIndex(windows, i);
CFNumberRef spacenum = CFDictionaryGetValue(windict, kCGWindowWorkspace);
if (spacenum) {
CFNumberGetValue(spacenum, kCFNumberIntType, &space);
return space;
return -1;
void set_space_by_index(int space)
CFNotificationCenterRef nc = CFNotificationCenterGetDistributedCenter();
CFStringRef numstr = CFStringCreateWithFormat(NULL, nil, CFSTR("%d"), space);
CFNotificationCenterPostNotification(nc, CFSTR(""), numstr, NULL, TRUE);
int main (int argc, char * const argv[])
int useCGS = 0, ch, space;
while ((ch = getopt(argc, argv, "-c")) != -1) {
switch (ch) {
case 'c':
useCGS = 1;
argc -= optind;
argv += optind;
if (argc > 0) {
space = atoi(argv[0]);
if (useCGS) CGSSetWorkspace(_CGSDefaultConnection(), space);
else set_space_by_index(space);
} else {
if (useCGS) CGSGetWorkspace(_CGSDefaultConnection(), &space);
else space = get_space_id();
printf("%d\n", space);
return 0;

Hey, thanks for this work. I am using the Slate window manager, and working with the javascript api it exposes. I am on Lion. This makes an acceptable bridge to overcome the fact that Slate can't handle spaces. My usecases revolve around being able to customize desktops/spaces for configuration and recognizing which space is current, as to Slate this is the global context. Not ideal, but cool with your work..

I understand this approach will not work with Mountain Lion/Mavericks from comments on StackOverflow, This is not yet my problem, but is too bad if that is true. Anyway, thanks for publishing this.

Have a good one,

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment