How to Export ChatGPT, Claude, Gemini & DeepSeek Chats to Obsidian Markdown (Without Breaking LaTeX or Code Blocks)
If you use ChatGPT, Claude, Google Gemini, DeepSeek, or Perplexity for daily engineering work, architecture reviews, or mathematical proofs, you have almost certainly experienced the "browser tab graveyard": dozens of high-value problem-solving sessions trapped across five different web apps with inconsistent search and zero offline ownership.
The obvious move is archiving your best conversations into Obsidian as clean, local .md files with YAML frontmatter. Yet anyone who has tried highlighting an AI thread and pressing Ctrl+C -> Ctrl+V into Obsidian knows how fast that breaks down:
- KaTeX & MathJax equations duplicate into unreadable gibberish (
E = mc^2E=mc2or stripped fractions with raw MathML tokens). - UI chrome leaks straight into your prose (
Copy code,pythonCopy code, thumbs-up/down button labels, and citation pills). - Nested triple backticks shatter code blocks whenever an AI writes a Markdown tutorial or README inside a fenced code block.
- GFM tables collapse into broken plain text or split rows whenever a cell contains a raw newline or unescaped pipe
|. - DeepSeek R1 reasoning traces and Perplexity reference lists flatten into wall-of-text paragraphs with no metadata linking back to the original session.
When we built ChatVault Pro at NiNo Studio — a 100% local Chrome Manifest V3 extension with zero cloud backend — we had to solve every single one of those DOM quirks cleanly across all five AI platforms. Below is the exact engineering breakdown of how AI chat DOMs actually store LaTeX, code languages, and tables, along with drop-in JavaScript patterns and an Obsidian Dataview workflow you can use immediately.
1. Why Standard Copy-Paste Corrupts LaTeX Across AI Platforms
Most AI chat interfaces do not render plain LaTeX text into the visible DOM. They render math through three completely different DOM pipelines:
- ChatGPT, Claude, DeepSeek, and Perplexity (KaTeX): KaTeX renders two sibling trees inside every
.katexwrapper — an invisible.katex-mathmltree (for screen readers) and a visual.katex-htmltree (positioned CSS spans). When you copy visible text from the browser, Chrome concatenates both trees, producing doubled symbols and broken exponents. - Google Gemini (Custom Math Attributes): Gemini frequently attaches the raw TeX source directly onto a wrapper element via
data-mathordata-latexattributes while rendering styled spans inside. - MathJax-based Web Interfaces (
<mjx-container>): MathJax injects SVG or CHTML glyph output alongside an optional<script type="math/tex">oraria-labelfallback.
The secret to lossless LaTeX extraction is never reading .textContent from rendered math glyphs. Instead, inspect the semantic source node before recursing into child elements and short-circuit traversal once the raw TeX is captured:
function extractLatexFromElement(el) { if (!el || el.nodeType !== 1) return null; const tag = (el.tagName || '').toLowerCase(); const classes = (el.getAttribute('class') || '').trim().split(/\s+/).filter(Boolean); // 1. Gemini / custom data-math or data-latex attributes const dataMath = el.getAttribute('data-math') || el.getAttribute('data-latex'); if (dataMath && dataMath.trim()) { const isBlock = classes.includes('math-block') || classes.includes('katex-display') || el.getAttribute('display') === 'true' || el.getAttribute('data-display') === 'block' || tag === 'div' || tag === 'p'; return { tex: dataMath.trim(), display: isBlock }; } // 2. KaTeX display & inline wrappers (.katex-display / .katex) if (classes.includes('katex-display') || classes.includes('katex')) { const ann = el.querySelector?.('annotation[encoding="application/x-tex"], annotation'); if (ann && ann.textContent.trim()) { const parentIsDisplay = classes.includes('katex-display') || Boolean(el.parentElement?.classList?.contains('katex-display')); return { tex: ann.textContent.trim(), display: parentIsDisplay }; } } // 3. MathJax <mjx-container> if (tag === 'mjx-container') { const script = el.querySelector?.('script[type^="math/tex"]'); const tex = script?.textContent?.trim() || el.getAttribute('data-tex') || el.getAttribute('aria-label') || ''; if (tex) { const isDisplay = el.getAttribute('display') === 'true' || Boolean(script && (script.getAttribute('type') || '').includes('mode=display')); return { tex, display: isDisplay }; } } return null; } Once extracted, format inline equations with single dollars ($E = mc^2$) and block equations on isolated lines with double dollars:
$$ \mathcal{L}(\theta) = -\frac{1}{N}\sum_{i=1}^{N} \log p_\theta(y_i \mid x_i) $$ Obsidian-specific detail: Obsidian's built-in MathJax renderer strictly dislikes spaces immediately inside inline delimiters ($ x $ fails to render in several contexts, whereas $x$ renders reliably everywhere) and treats \(...\) or \[...\] inconsistently compared to $...$ and $$...$$. Normalizing both inline and display delimiters during export prevents 95% of broken math notes in Obsidian.
2. Preserving Code Languages & Solving the Nested Triple-Backtick Bug
When you paste code out of ChatGPT or Claude into a plain Markdown file, two frustrating issues happen constantly:
- The language header gets glued to the first line (
pythonCopy codeimport os) because the<pre>container includes a toolbar<div>with the language badge and a<button>Copy code</button>. - Markdown-inside-Markdown breaks fencing. If Claude generates a
SKILL.mdorREADME.mdcontaining triple-backtick code fences (bash `), wrapping the whole block in another `markdownfence prematurely terminates the block in Obsidian!
Fixing both requires two clean rules:
- Skip interactive UI tags globally (
button,nav,select,form,style,noscript,template) before extracting text. - Dynamically size the outer fence by scanning the code body for the longest consecutive run of backticks and using
max(3, longestRun + 1)backticks — valid CommonMark and 100% supported by Obsidian:
function formatCodeFence(code, lang = '') { const cleaned = code.replace(/\r\n/g, '\n').replace(/\n$/, ''); const matches = cleaned.match(/`{3,}/g); const maxRun = matches ? Math.max(...matches.map((m) => m.length)) : 0; const fence = '`'.repeat(Math.max(3, maxRun + 1)); return `\n\n${fence}${lang}\n${cleaned}\n${fence}\n\n`; } If the inner code contains `, `formatCodeFence()` automatically wraps it in four backticks (`markdown ...`). Obsidian renders the outer fence cleanly and preserves every inner snippet intact.
For language detection across all five AI platforms, check sources in priority order:
- Direct attributes:
data-language,data-lang,data-code-lang - Class prefixes on
<code>or<pre>:language-typescript,lang-python - Platform header bars immediately preceding
<code>:.md-code-block-infostring(DeepSeek),.code-block-decoration span(Gemini),[data-testid="code-language"](Claude), or the first header<span>inside ChatGPT's<pre>wrapper — stripping any trailingcopy codetext and mapping aliases (py->python,ts->typescript,sh->bash,c++->cpp).
3. Keeping GFM Tables & Links Safe Inside Your Vault
AI models love summarizing architecture tradeoffs in Markdown tables. When converting an HTML <table> back to GitHub-Flavored Markdown for Obsidian, watch for two common edge cases:
- Multi-line table cells: A raw
\ninside a Markdown pipe table splits the row in half and breaks the entire table. Replace internal line breaks inside<th>and<td>cells with<br>. - Literal pipes inside cells: TypeScript union types (
string | number) or Bash pipelines inside a cell must be escaped as\|so Obsidian doesn't miscount columns. - Unsafe URI schemes: When archiving web-grounded Perplexity or Gemini answers, sanitize
hrefandsrcvalues by stripping control characters and rejectingjavascript:,vbscript:, anddata:text/htmllinks before writing the.mdfile.
4. Designing an Obsidian YAML Frontmatter Schema That Scales to 1,000+ Chats
Exporting a chat as bare Markdown solves today's copy-paste headache, but structured YAML frontmatter is what turns a dump of .md files into a real second brain.
Here is the exact Obsidian frontmatter template we standardized in ChatVault Pro:
`yaml
title: "PostgreSQL Partial Index Strategy for Multi-Tenant SaaS"
platform: claude
source_url: "https://claude.ai/chat/example-thread-id"
captured_at: 2026-12-04T14:22:00Z
folder: "Engineering/Databases"
message_count: 14
tags:
- ai-chat
- claude
- postgres
- performance
`
Why these exact seven fields? Because once every archived thread carries platform, folder, captured_at, and tags, you can drop a single Obsidian Dataview dashboard note at the root of your vault (AI Knowledge Index.md) and query every AI session you have ever saved across all five providers:
`markdown
Recent AI Architecture & Debugging Threads
dataview
TABLE platform AS "Model", folder AS "Topic", message_count AS "Turns", captured_at AS "Saved"
FROM #ai-chat
SORT captured_at DESC
LIMIT 25
`
Pair that with Obsidian's native graph view or [[wikilinks]] inside a short ## Key Takeaways section at the top of each exported note, and a 20-minute debugging session with DeepSeek R1 or Claude immediately becomes permanent, grep-able team documentation.
5. Manual Cleaning vs. 100% Local Browser Automation
If you only archive one or two conversations a week, you can paste raw copied text through a lightweight browser-only cleaner that strips Copy code noise, normalizes \(...\) / \[...\] LaTeX into Obsidian $...$ / $$...$$, and prepends valid YAML frontmatter — without sending your private code or prompts to any external server.
If you archive threads daily across ChatGPT, Claude, Gemini, DeepSeek (including R1 reasoning blocks), and Perplexity (including source citations), doing DOM cleanup manually gets old fast — especially when you want:
- 1-click Obsidian YAML Markdown export directly from the live DOM (zero KaTeX duplication, exact code languages, escaped GFM tables)
- Print-ready HTML / Save-as-PDF reports with framed code cards and clean
@media printpage breaks - A private, full-text searchable IndexedDB Knowledge Vault inside Chrome's Side Panel with folders, tags, and 1-click Batch ZIP export (including an auto-generated
_INDEX.md) - Zero cloud accounts, zero telemetry, zero subscriptions — everything runs 100% client-side in Chrome Manifest V3 using minimal
activeTab+scriptingpermissions (only touching the current tab when you explicitly click export)
That is exactly why we built ChatVault Pro at NiNo Studio:
- ChatVault Pro — Lifetime License ($19 one-time, no monthly fee): https://vietanh63.gumroad.com/l/chatvault-pro
- ChatVault Pro — Full Commercial MV3 Source Code ($49, zero runtime npm deps + 30 automated unit tests): https://vietanh63.gumroad.com/l/chatvault-pro-source
- Follow NiNo Studio Releases & Our 30-Day AI Survival Challenge: X (@NiNoAI_30) · Telegram Release Channel
Quick Obsidian Import Checklist
Before archiving your next high-value AI thread, run through this 5-point sanity check:
- Check every math block: Confirm inline
$...$has no stray leading/trailing spaces and display$$...$$sits on its own blank-line-delimited block. - Verify nested fences: Any response containing Markdown examples should use 4+ backticks for the outer fence.
- Strip UI noise: Confirm zero
Copy code,Edit, orRegeneratestrings leaked into code blocks. - Preserve provenance: Include
platformandsource_urlin YAML frontmatter so you can revisit the original thread if needed. - Keep sensitive code local: Never paste proprietary company source code or API schemas into cloud-hosted "AI chat exporter" SaaS sites when a local browser pipeline keeps 100% of your data on disk.