From 3ce9f0200737648afb662ff1c9cd49d09a6bae67 Mon Sep 17 00:00:00 2001 From: Le Tan Date: Wed, 21 Dec 2016 21:37:33 +0800 Subject: [PATCH] clear corrupted image preview block Users may add some texts in the image preview block around the image. In this case, we should just delete the image and insert another preview block. Signed-off-by: Le Tan --- src/vmdedit.cpp | 30 ++++++++++++++++++++++++++++++ src/vmdedit.h | 2 ++ 2 files changed, 32 insertions(+) diff --git a/src/vmdedit.cpp b/src/vmdedit.cpp index bc042608..e84e005d 100644 --- a/src/vmdedit.cpp +++ b/src/vmdedit.cpp @@ -244,6 +244,7 @@ void VMdEdit::clearOrphanImagePreviewBlock() removeBlock(block); block = nextBlock; } else { + clearCorruptedImagePreviewBlock(block); block = block.next(); } } @@ -268,6 +269,35 @@ bool VMdEdit::isOrphanImagePreviewBlock(QTextBlock p_block) return false; } +void VMdEdit::clearCorruptedImagePreviewBlock(QTextBlock p_block) +{ + if (!p_block.isValid()) { + return; + } + QString text = p_block.text(); + QVector replacementChars; + bool onlySpaces = true; + for (int i = 0; i < text.size(); ++i) { + if (text[i] == QChar::ObjectReplacementCharacter) { + replacementChars.append(i); + } else if (!text[i].isSpace()) { + onlySpaces = false; + } + } + if (!onlySpaces && !replacementChars.isEmpty()) { + // ObjectReplacementCharacter mixed with other non-space texts. + // Users corrupt the image preview block. Just remove the char. + QTextCursor cursor(p_block); + int blockPos = p_block.position(); + for (int i = replacementChars.size() - 1; i >= 0; --i) { + int pos = replacementChars[i]; + cursor.setPosition(blockPos + pos); + cursor.deleteChar(); + } + Q_ASSERT(text.remove(QChar::ObjectReplacementCharacter) == p_block.text()); + } +} + QString VMdEdit::fetchImageToPreview(const QString &p_text) { QRegExp regExp("\\!\\[[^\\]]*\\]\\((images/[^/\\)]+)\\)"); diff --git a/src/vmdedit.h b/src/vmdedit.h index 7eb40c31..9109546a 100644 --- a/src/vmdedit.h +++ b/src/vmdedit.h @@ -60,6 +60,8 @@ private: void clearOrphanImagePreviewBlock(); void removeBlock(QTextBlock p_block); bool isOrphanImagePreviewBlock(QTextBlock p_block); + // Block that has the QChar::ObjectReplacementCharacter as well as some non-space characters. + void clearCorruptedImagePreviewBlock(QTextBlock p_block); // Returns the image relative path (image/xxx.png) only when // there is one and only one image link. QString fetchImageToPreview(const QString &p_text);