diff --git a/src/plugins/texteditor/syntaxhighlighter.cpp b/src/plugins/texteditor/syntaxhighlighter.cpp
index fbc67d42fc168b9575ad7f54775861dcfed0f688..b02d6ef9c6c53e8597ff6e6ac87fc1840968559a 100644
--- a/src/plugins/texteditor/syntaxhighlighter.cpp
+++ b/src/plugins/texteditor/syntaxhighlighter.cpp
@@ -684,7 +684,12 @@ void SyntaxHighlighter::setExtraAdditionalFormats(const QTextBlock& block,
     if (block.layout() == 0)
         return;
 
-    QList<QTextLayout::FormatRange> formats = fmts;
+    QList<QTextLayout::FormatRange> formats;
+    formats.reserve(fmts.size());
+    foreach (QTextLayout::FormatRange r, fmts) {
+        r.format.setProperty(QTextFormat::UserProperty, true);
+        formats.append(r);
+    }
     qSort(formats.begin(), formats.end(), byStartOfRange);
 
     QList<QTextLayout::FormatRange> previousSemanticFormats;
@@ -698,19 +703,12 @@ void SyntaxHighlighter::setExtraAdditionalFormats(const QTextBlock& block,
             formatsToApply.append(r);
     }
 
-    qSort(previousSemanticFormats.begin(), previousSemanticFormats.end(), byStartOfRange);
-
-    foreach (QTextLayout::FormatRange r, formats) {
-        r.format.setProperty(QTextFormat::UserProperty, true);
-        formatsToApply.append(r);
-    }
-
     if (formats.size() == previousSemanticFormats.size()) {
+        qSort(previousSemanticFormats.begin(), previousSemanticFormats.end(), byStartOfRange);
+
         int index = 0;
         for (; index != formats.size(); ++index) {
-            QTextLayout::FormatRange range = formats.at(index);
-            range.format.setProperty(QTextFormat::UserProperty, true);
-
+            const QTextLayout::FormatRange &range = formats.at(index);
             const QTextLayout::FormatRange &previousRange = previousSemanticFormats.at(index);
 
             if (range.start != previousRange.start ||
@@ -723,6 +721,8 @@ void SyntaxHighlighter::setExtraAdditionalFormats(const QTextBlock& block,
             return;
     }
 
+    formatsToApply += formats;
+
     bool wasInReformatBlocks = d->inReformatBlocks;
     d->inReformatBlocks = true;
     block.layout()->setAdditionalFormats(formatsToApply);