diff --git a/lib/codemirror.js b/lib/codemirror.js
index 5591cd6d43cbfde90ee7c17b9fae6d229a3eaf52..89401a9760c65b00e854ec1d046ea63702b4864a 100644
--- a/lib/codemirror.js
+++ b/lib/codemirror.js
@@ -2665,7 +2665,12 @@ var CodeMirror = (function() {
             outPos += l;
             span_(text, style);
             // Output empty wrapper when at end of line
-            if (outPos == wrapAt && outPos == len) html.push(open + (gecko ? "&#x200b;" : " ") + "</span>");
+            // (Gecko and IE8+ do strange wrapping when adding a space
+            // to the end of the line. Other browsers don't react well
+            // to zero-width spaces. So we do hideous browser sniffing
+            // to determine which to use.)
+            if (outPos == wrapAt && outPos == len)
+              html.push(open + (gecko || (ie && !ie_lt8) ? "&#x200b;" : " ") + "</span>");
             // Stop outputting HTML when gone sufficiently far beyond measure
             else if (outPos > wrapAt + 10 && /\s/.test(text)) span = function(){};
           }