--- src/imapd/imapd.c.BAK	2013-05-10 00:13:25.000000000 +0200
+++ src/imapd/imapd.c	2013-05-10 00:26:27.000000000 +0200
@@ -937,31 +937,50 @@
 
 				/* wants ALL */
 		if (retval & 0x4) {
-		  unsigned long j;
+		  unsigned long muids, muid1, muid2;
 				/* find first match */
 		  for (i = 1; (i <= nmsgs) && !mail_elt (stream,i)->searched;
 		       ++i);
 		  if (i <= nmsgs) {
 		    PSOUT (" ALL ");
-		    pnum (uid ? mail_uid (stream,i) : i);
-		    j = i;	/* last message output */
+		    muids = uid ? mail_uid (stream,i) : i;
+		    pnum (muids);
+		    muid1 = muids;
 		  }
 		  while (++i <= nmsgs) {
 		    if (mail_elt (stream,i)->searched) {
-		      while ((++i <= nmsgs) && mail_elt (stream,i)->searched);
-				/* previous message is end of range */
-		      if (j != --i) {
+		      muid2 = uid ? mail_uid (stream,i) : i;
+		      
+		      if (muids != 0 && muid2 == muid1 + 1 && i < nmsgs) {
+		        muid1 = muid2;
+		        continue;
+		      }
+		      
+		      if (muids == 0) {
+			PBOUT (',');
+		        pnum (muid2);
+		        muids = muid1 = muid2;
+		      } else if (muid2 != muid1 + 1) {
+			if (muid1 != muids) {
+			  PBOUT (':');
+		          pnum (muid1);
+			}
+			PBOUT (',');
+		        pnum (muid2);
+		        muids = muid1 = muid2;
+		      } else {
 			PBOUT (':');
-			pnum (uid ? mail_uid (stream,i) : i);
+		        pnum (muid2);
+		        muids = 0;
+		        muid1 = muid2;
 		      }
-		    }
-				/* search for next match */
-		    while ((++i <= nmsgs) && !mail_elt (stream,i)->searched);
-		    if (i <= nmsgs) {
-		      PBOUT (',');
-		      pnum (uid ? mail_uid (stream,i) : i);
-		      j = i;	/* last message output */
-		    }
+                    } else {
+                      if (muids != 0 && muid1 != muids) {
+			PBOUT (':');
+		        pnum (muid1);
+		        muids = 0;
+                      }
+                    }
 		  }
 		}
 				/* wants COUNT */