I have created a html chat app that generates messages from an API in real time. I used katex to render it's maths and use markjs to markdown. Now problem is that when API sends a code through code. Inside the code block katex tags become visible for even though there is no maths there. It happens only inside the code blocks. How can I stop this?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Of course! This is a very common issue when combining a Markdown parser with a math rendering library.
The problem happens because of the order of operations:
Marked.js runs first. It takes your raw text and converts code into <pre><code>...</code></pre> HTML tags.
KaTeX's auto-render extension runs second. It scans the entire message element for math delimiters (like $) and tries to render them. It doesn't know that it should ignore the content inside the <pre><code> tags that Marked.js just created.
The Best Solution: Use KaTeX's ignoredTags Option
The KaTeX auto-render extension was built to handle this exact scenario. You can provide an options object to the renderMathInElement function and tell it which HTML tags to ignore.
You need to tell KaTeX to ignore code, pre, and script tags.
Here is how you would modify your KaTeX call:
javascript
// This is the function that likely gets called when a new message arrives
function displayNewMessage(rawMarkdown) {
const messageContainer = document.getElementById('chat-messages');
const newMessageDiv = document.createElement('div');
newMessageDiv.className = 'message';
// 1. Parse the Markdown into HTML using Marked.js
// Note: I'm assuming you are using `marked.js`. If you are truly using `mark.js` (for highlighting),
// the principle is the same: first convert markdown, then render math.
newMessageDiv.innerHTML = marked.parse(rawMarkdown);
// 2. Append the new message to the chat container
messageContainer.appendChild(newMessageDiv);
// 3. Render math IN THE NEW MESSAGE, ignoring code blocks
// THIS IS THE CRITICAL PART
renderMathInElement(newMessageDiv, {
delimiters: [
{left: '$$', right: '$$', display: true},
{left: '$', right: '$', display: false},
{left: '\\(', right: '\\)', display: false},
{left: '\\[', right: '\\]', display: true}
],
// This is the key that solves your problem!
ignoredTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
});
// Scroll to the bottom
messageContainer.scrollTop = messageContainer.scrollHeight;
}
By adding the ignoredTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code'] option, you explicitly instruct KaTeX's auto-render script to not even look for math inside those elements. This will prevent it from seeing the dollar signs or other symbols inside your code blocks.
Complete, Run-able Example
Here is a full HTML file you can save and open in your browser to see it working.
html
By using the ignoredTags option, you get the best of both worlds: robust math rendering where you want it and plain, un-touched code where it's supposed to be.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chat App Demo</title>
<!-- KaTeX CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css" integrity="sha384-n8MVd4RsNIU0KOVEMea+LdwRmycECOjzpbM2Zm+5Bz4imZSIIMeAPnSoxMje+d5i" crossorigin="anonymous">
<!-- KaTeX JS and Auto-render extension -->
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.js" integrity="sha384-XjKyOOlGwcjNTAIQHIpgOno0Hl1YQqzUOEleOLALmuqehneUG+vnGohHnVLTxUS+" crossorigin="anonymous"></script>
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/contrib/auto-render.min.js" integrity="sha384-+VBxd3r6XgURycqtZ117nYw44OOcIax56Z4dCRWbxyPt0Koah1uHoK0o4+/RRE05" crossorigin="anonymous"></script>
<!-- Marked.js for Markdown -->
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<style>
body { font-family: sans-serif; line-height: 1.6; }
#chat-window { border: 1px solid #ccc; max-width: 600px; margin: 20px auto; }
#messages { height: 400px; overflow-y: auto; padding: 10px; border-bottom: 1px solid #ccc; }
.message { margin-bottom: 15px; padding: 10px; background-color: #f1f1f1; border-radius: 5px; }
pre { background-color: #2d2d2d; color: #f1f1f1; padding: 15px; border-radius: 5px; overflow-x: auto; }
code { font-family: 'Courier New', Courier, monospace; }
pre code { padding: 0; background: none; }
</style>
</head>
<body>
<div id="chat-window">
<div id="messages"></div>
</div>
<script>
// This is the function that processes and displays a new message
function processAndDisplayMessage(markdownContent) {
const messagesContainer = document.getElementById('messages');
const newMessage = document.createElement('div');
newMessage.className = 'message';
// 1. Convert Markdown to HTML
newMessage.innerHTML = marked.parse(markdownContent);
// 2. Append to the DOM
messagesContainer.appendChild(newMessage);
// 3. Render Math, but IGNORE content inside <pre> and <code> tags
renderMathInElement(newMessage, {
delimiters: [
{left: '$$', right: '$$', display: true},
{left: '$', right: '$', display: false}
],
// THIS IS THE FIX:
ignoredTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
});
// Auto-scroll to the bottom
messagesContainer.scrollTop = messagesContainer.scrollHeight;
}
// --- SIMULATE API MESSAGES ---
// Message with both math and a code block containing a '$'
const apiMessage = `
Hello! Here is the famous equation for energy: $E=mc^2$.
And here is some shell script code. Notice the dollar sign for the variable. Without the fix, KaTeX would try to render it.
\`\`\`bash
# This is a comment inside a code block
echo "Your home directory is: $HOME"
# Another variable: $USER
\`\`\`
As you can see, the equation $E=mc^2$ is rendered, but the \`$HOME\` variable inside the code block is left alone.
`;
// Simulate receiving the message after a short delay
setTimeout(() => {
processAndDisplayMessage(apiMessage);
}, 500);
</script>
</body>
</html>