Perfect, You will see my code applies the format correctly and works correctly outside of tables, but I found out instead of doing this:
richTextChatBox->BeginBold();
richTextChatBox->WriteText(styledText);
richTextChatBox->EndBold();
We can do this:
wxRichTextAttr textAttr = wxRichTextAttr(style);
cellAttr.SetFontWeight(wxFONTWEIGHT_BOLD);
richTextChatBox->BeginStyle(textAttr);
richTextChatBox->EndStyle();
So moving from the first method to the second, will help us dealing with the way tables are done, since you can't use BeginX methods inside the table writting and you have to use styles instead. So we have to find a way to modify the original code to do it in this way.
Here is my currently working code, remember the table format part is not finished and only the bold text is done for reference purpose only:
namespace Markdown
{
wxArrayString FilterEmptyElements(const wxArrayString& arrayString);
wxString DetectAndMarkTables(const wxString& message);
void CreateAndInsertTable(wxRichTextCtrl* richTextChatBox, const wxString& tableData, const wxTextAttr& style);
wxString ReplaceUnpaired(wchar_t character, wchar_t replaceCharacter, const wxString& message);
wxString FormatMessage(const wxString& message);
void WriteText(wxRichTextCtrl* richTextChatBox, const wxString& message, const wxTextAttr& style);
};
namespace
{
// all the markdown constants used are defined here.
}
wxArrayString Markdown::FilterEmptyElements(const wxArrayString& arrayString)
{
wxArrayString filteredArrayString;
for (const wxString& s : arrayString)
{
if (!s.IsEmpty())
{
filteredArrayString.Add(wxString(s).Trim(false).Trim());
}
}
return filteredArrayString;
}
wxString Markdown::DetectAndMarkTables(const wxString& message)
{
wxString output;
wxString currentTable;
bool inTable = false;
wxString::size_type pos = 0;
while (pos < message.Length())
{
wxString::size_type lineEnd = message.find('\n', pos);
if (lineEnd == wxString::npos) lineEnd = message.Length();
wxString line = message.substr(pos, lineEnd - pos).Trim(false).Trim();
if (line.StartsWith(TABLE_COLUMN_MARKER))
{
if (!inTable)
{
inTable = true;
currentTable.clear();
output << TABLE_MARKER; // Mark the start of a table
}
currentTable << line << '\n';
}
else if (inTable && line.StartsWith(TABLE_HEADER_MARKER))
{
currentTable << line << '\n';
}
else
{
if (inTable)
{
inTable = false;
output << currentTable << TABLE_MARKER; // Mark the end of a table
currentTable.clear();
}
output << line << '\n';
}
pos = lineEnd + 1;
}
if (inTable)
{
output << currentTable << TABLE_MARKER;
}
return output;
}
void Markdown::CreateAndInsertTable(wxRichTextCtrl* richTextChatBox, const wxString& tableData, const wxTextAttr& style)
{
wxArrayString rows = wxSplit(tableData, '\n');
if (rows.empty()) return;
wxArrayString headers = wxSplit(rows[0], TABLE_COLUMN_MARKER[0]);
headers = FilterEmptyElements(headers);
wxString::size_type colsCount = headers.GetCount();
wxString::size_type rowsCount = rows.GetCount() - 2; // Exclude header underline
if (colsCount < 2)
{
return;
}
wxRichTextTable* table = richTextChatBox->WriteTable(rowsCount, colsCount);
// Headers
for (wxString::size_type col = 0; col < colsCount; ++col)
{
wxRichTextAttr cellAttr = wxRichTextAttr(style);
cellAttr.SetAlignment(wxTEXT_ALIGNMENT_CENTRE);
cellAttr.SetFontWeight(wxFONTWEIGHT_BOLD);
table->GetCell(0, col)->AddParagraph(headers[col].Trim(false).Trim(), &cellAttr);
}
for (wxString::size_type row = 1; row < rowsCount; ++row)
{
wxArrayString cells = wxSplit(rows[row + 1], TABLE_COLUMN_MARKER[0]); // Skip header row
cells = FilterEmptyElements(cells);
if (cells.GetCount() != colsCount)
{
continue;
}
for (wxString::size_type col = 0; col < colsCount; ++col)
{
wxRichTextAttr cellAttr = wxRichTextAttr(style);
cellAttr.SetAlignment(wxTEXT_ALIGNMENT_CENTRE);
table->GetCell(row, col)->AddParagraph(cells[col].Trim(false).Trim(), &cellAttr);
}
}
}
wxString Markdown::ReplaceUnpaired(wchar_t character, wchar_t replaceCharacter, const wxString& message)
{
wxString output;
for (wxString::size_type i = 0; i < message.length(); ++i)
{
if (message[i] == '\n' && message[i + 1] == character)
{
wxString::size_type nextChar = message.find(character, i + 2);
if (nextChar == wxString::npos || nextChar >= message.find('\n', i + 2))
{
output << message[i] << replaceCharacter << ' ';
i += 1;
continue;
}
}
output << message[i];
}
return output;
}
wxString Markdown::FormatMessage(const wxString& message)
{
wxString formattedMessage = message;
formattedMessage.Replace(LINE_BREAK_TAG, "\n");
formattedMessage.Replace(START_BOLD_TAG, BOLD_MARKER);
formattedMessage.Replace(END_BOLD_TAG, BOLD_MARKER);
formattedMessage.Replace(START_ITALIC_TAG, ITALIC_MARKER);
formattedMessage.Replace(END_ITALIC_TAG, ITALIC_MARKER);
formattedMessage.Replace(START_LIST_MARKER, LIST_MARKER);
formattedMessage = Markdown::ReplaceUnpaired('*', LIST_MARKER[1], formattedMessage);
formattedMessage = DetectAndMarkTables(formattedMessage);
return formattedMessage;
}
void Markdown::WriteText(wxRichTextCtrl* richTextChatBox, const wxString& message, const wxTextAttr& style)
{
richTextChatBox->BeginStyle(style);
wxString formattedMessage = Markdown::FormatMessage(message);
wxString::size_type pos = 0;
while (pos < formattedMessage.Length() && pos != wxString::npos)
{
wxString::size_type startBoldItalic = formattedMessage.find(BOLD_ITALIC_MARKER, pos);
wxString::size_type startBold = formattedMessage.find(BOLD_MARKER, pos);
wxString::size_type startItalic = formattedMessage.find(ITALIC_MARKER, pos);
wxString::size_type startUnderline = formattedMessage.find(UNDERLINE_MARKER, pos);
wxString::size_type startLinkText = formattedMessage.find(START_LINK_TEXT_MARKER, pos);
wxString::size_type startCode = formattedMessage.find(CODE_MARKER, pos);
wxString::size_type startStrikethrough = formattedMessage.find(STRIKETHROUGH_MARKER, pos);
wxString::size_type startTable = formattedMessage.find(TABLE_MARKER, pos);
wxString::size_type startHeadings[] = {
formattedMessage.find(pos == 0 ? HEADING_MARKERS[0] : ("\n" + HEADING_MARKERS[0]), pos),
formattedMessage.find(pos == 0 ? HEADING_MARKERS[1] : ("\n" + HEADING_MARKERS[1]), pos),
formattedMessage.find(pos == 0 ? HEADING_MARKERS[2] : ("\n" + HEADING_MARKERS[2]), pos),
formattedMessage.find(pos == 0 ? HEADING_MARKERS[3] : ("\n" + HEADING_MARKERS[3]), pos),
formattedMessage.find(pos == 0 ? HEADING_MARKERS[4] : ("\n" + HEADING_MARKERS[4]), pos),
formattedMessage.find(pos == 0 ? HEADING_MARKERS[5] : ("\n" + HEADING_MARKERS[5]), pos)
};
wxString::size_type startBlockquote = formattedMessage.find(pos == 0 ? BLOCKQUOTE_MARKER : ("\n" + BLOCKQUOTE_MARKER), pos);
std::vector<std::pair<wxString::size_type, int>> markers = {
{ startBoldItalic, 3 },
{ startBold, 2 },
{ startItalic, 1 },
{ startUnderline, 2 },
{ startCode, 1 },
{ startHeadings[5], 7 },
{ startHeadings[4], 6 },
{ startHeadings[3], 5 },
{ startHeadings[2], 4 },
{ startHeadings[1], 3 },
{ startHeadings[0], 2 },
{ startBlockquote, 2 },
{ startStrikethrough, 2 },
{ startLinkText, -1 },
{ startTable, 0 }
};
// Find the earliest marker
auto earliestIt = std::min_element(markers.begin(), markers.end(), [](const auto& lhs, const auto& rhs){
return (lhs.first != wxString::npos && (rhs.first == wxString::npos || lhs.first < rhs.first));
});
if (earliestIt->first != wxString::npos)
{
wxString::size_type markerPos = earliestIt->first;
int markerLength = earliestIt->second;
wxString::size_type endMarker;
if (startBoldItalic == markerPos)
{
endMarker = formattedMessage.find(BOLD_ITALIC_MARKER, markerPos + markerLength);
}
else if (startBold == markerPos)
{
endMarker = formattedMessage.find(BOLD_MARKER, markerPos + markerLength);
}
else if (startUnderline == markerPos)
{
endMarker = formattedMessage.find(UNDERLINE_MARKER, markerPos + markerLength);
}
else if (startItalic == markerPos)
{
endMarker = formattedMessage.find(ITALIC_MARKER, markerPos + markerLength);
}
else if (startCode == markerPos)
{
endMarker = formattedMessage.find(CODE_MARKER, markerPos + markerLength);
}
else if (startStrikethrough == markerPos)
{
endMarker = formattedMessage.find(STRIKETHROUGH_MARKER, markerPos + markerLength);
}
else if (startHeadings[0] == markerPos || startHeadings[1] == markerPos || startHeadings[2] == markerPos || startHeadings[3] == markerPos || startHeadings[4] == markerPos || startHeadings[5] == markerPos || startBlockquote == markerPos)
{
endMarker = formattedMessage.find("\n", markerPos + markerLength);
}
else if (startTable == markerPos)
{
wxString::size_type tableEnd = formattedMessage.find(TABLE_MARKER, markerPos + TABLE_MARKER.length());
if (tableEnd != wxString::npos)
{
wxString tableData = formattedMessage.substr(markerPos + TABLE_MARKER.length(), tableEnd - (markerPos + TABLE_MARKER.length()));
CreateAndInsertTable(richTextChatBox, tableData, style);
pos = tableEnd + TABLE_MARKER.length();
continue;
}
else
{
richTextChatBox->WriteText(formattedMessage.substr(pos));
pos = wxString::npos;
continue;
}
}
else if (startLinkText == markerPos)
{
wxString::size_type endLinkText = formattedMessage.find(END_LINK_TEXT_MARKER, markerPos);
wxString::size_type startLinkUrl = formattedMessage.find(START_LINK_URL_MARKER, endLinkText);
wxString::size_type endLinkUrl = formattedMessage.find(END_LINK_URL_MARKER, startLinkUrl);
if (endLinkText != wxString::npos && startLinkUrl != wxString::npos && endLinkUrl != wxString::npos)
{
wxString beforeMarker = formattedMessage.substr(pos, markerPos - pos);
wxString linkText = formattedMessage.substr(markerPos + 1, endLinkText - markerPos - 1);
wxString linkUrl = formattedMessage.substr(startLinkUrl + 1, endLinkUrl - startLinkUrl - 1);
if (linkUrl.StartsWith("http://") || linkUrl.StartsWith("https://"))
{
richTextChatBox->WriteText(beforeMarker);
wxRichTextAttr urlStyle;
urlStyle.SetTextColour(*wxBLUE);
urlStyle.SetFontUnderlined(true);
richTextChatBox->BeginStyle(urlStyle);
richTextChatBox->BeginURL(linkUrl);
richTextChatBox->WriteText(linkText);
richTextChatBox->EndURL();
richTextChatBox->EndStyle();
pos = endLinkUrl + 1;
continue;
}
else
{
wxString invalidLinkText = formattedMessage.substr(markerPos, endLinkUrl - markerPos + 1);
richTextChatBox->WriteText(beforeMarker + invalidLinkText);
pos = endLinkUrl + 1;
continue;
}
}
}
if (endMarker != wxString::npos)
{
wxString beforeMarker = formattedMessage.substr(pos, markerPos - pos);
richTextChatBox->WriteText(beforeMarker);
wxString styledText = formattedMessage.substr(markerPos + markerLength, endMarker - markerPos - markerLength);
if (startBoldItalic == markerPos || startBold == markerPos || startUnderline == markerPos) // Bold and/or Underline
{
if (startBoldItalic == markerPos)
{
richTextChatBox->BeginBold();
richTextChatBox->BeginUnderline();
}
else if (startBold == markerPos)
{
richTextChatBox->BeginBold();
}
else if (startUnderline == markerPos)
{
richTextChatBox->BeginUnderline();
}
richTextChatBox->WriteText(styledText);
if (startBoldItalic == markerPos)
{
richTextChatBox->EndBold();
richTextChatBox->EndUnderline();
}
else if (startBold == markerPos)
{
richTextChatBox->EndBold();
}
else if (startUnderline == markerPos)
{
richTextChatBox->EndUnderline();
}
}
else if (markerLength == 1 && startItalic == markerPos) // Italic
{
richTextChatBox->BeginItalic();
richTextChatBox->WriteText(styledText);
richTextChatBox->EndItalic();
}
else if (markerLength == 1 && startCode == markerPos) // Inline code
{
wxTextAttr codeAttr;
codeAttr.SetFontWeight(wxFONTWEIGHT_MEDIUM);
codeAttr.SetBackgroundColour(style.GetBackgroundColour().ChangeLightness(60));
codeAttr.SetTextColour(style.GetTextColour().ChangeLightness(140));
richTextChatBox->BeginStyle(codeAttr);
richTextChatBox->WriteText(styledText);
richTextChatBox->EndStyle();
}
else if (markerLength == 2 && startBlockquote == markerPos) // Blockquote
{
wxTextAttr blockquoteAttr;
blockquoteAttr.SetBackgroundColour(style.GetBackgroundColour().ChangeLightness(50));
blockquoteAttr.SetTextColour(wxColour(220, 220, 220));
richTextChatBox->BeginStyle(blockquoteAttr);
richTextChatBox->WriteText(styledText);
richTextChatBox->EndStyle();
if (endMarker < formattedMessage.Length() && formattedMessage[endMarker] == '\n')
{
richTextChatBox->WriteText("\n");
}
}
else if (markerLength == 2 && startStrikethrough == markerPos) // Strikethrough
{
wxFont font = richTextChatBox->GetFont();
font.MakeStrikethrough();
richTextChatBox->BeginFont(font);
richTextChatBox->WriteText(styledText);
richTextChatBox->EndFont();
}
else if (markerLength >= 2 && markerLength <= 7 && (startHeadings[0] == markerPos || startHeadings[1] == markerPos || startHeadings[2] == markerPos || startHeadings[3] == markerPos || startHeadings[4] == markerPos || startHeadings[5] == markerPos)) // Headings
{
wxFont font = richTextChatBox->GetFont();
int pointSize = font.GetPointSize();
if (startHeadings[0] == markerPos)
{
pointSize *= 2;
}
else if (startHeadings[1] == markerPos)
{
pointSize *= 1.7;
}
else if (startHeadings[2] == markerPos)
{
pointSize *= 1.5;
}
else if (startHeadings[3] == markerPos)
{
pointSize *= 1.3;
}
else if (startHeadings[4] == markerPos)
{
pointSize *= 1.2;
}
else if (startHeadings[5] == markerPos)
{
pointSize *= 1.1;
}
richTextChatBox->WriteText("\n");
richTextChatBox->BeginFontSize(pointSize);
richTextChatBox->WriteText(styledText);
richTextChatBox->EndFontSize();
richTextChatBox->WriteText("\n");
}
if (startHeadings[0] == markerPos || startHeadings[1] == markerPos || startHeadings[2] == markerPos || startHeadings[3] == markerPos || startHeadings[4] == markerPos || startHeadings[5] == markerPos)
{
pos = endMarker + 1;
}
else
{
pos = endMarker + markerLength;
}
}
else
{
richTextChatBox->WriteText(formattedMessage.substr(pos));
pos = wxString::npos;
}
}
else
{
richTextChatBox->WriteText(formattedMessage.substr(pos));
pos = wxString::npos;
}
}
richTextChatBox->EndStyle();
}