You.com KaTeX Copy Handler

Clean copy of KaTeX expressions without duplicates or extra line breaks

当前为 2025-04-11 提交的版本,查看 最新版本

// ==UserScript==
// @name         You.com KaTeX Copy Handler
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  Clean copy of KaTeX expressions without duplicates or extra line breaks
// @author       Assistant
// @match        *://*.you.com/*
// @grant        none
// @license MIT
// @icon         https://www.google.com/s2/favicons?sz=64&domain=you.com
// ==/UserScript==

(function() {
    'use strict';

    // Function to extract clean text from KaTeX element
    function extractKaTeXText(element) {
        // Get the LaTeX source from annotation if available
        const annotation = element.querySelector('.katex-mathml annotation[encoding="application/x-tex"]');
        if (annotation) {
            return annotation.textContent;
        }

        // Fallback: extract from visible content
        const baseElements = element.querySelectorAll('.katex-html .base .mord, .katex-html .base .mopen, .katex-html .base .mclose');
        return Array.from(baseElements).map(el => el.textContent).join('');
    }

    // Handle copy event
    document.addEventListener('copy', function(e) {
        const selection = window.getSelection();
        if (!selection.rangeCount) return;

        const range = selection.getRangeAt(0);
        const container = range.commonAncestorContainer;

        // Check if selection contains KaTeX
        const katexElement = container.closest('.katex') ||
                           container.querySelector('.katex');

        if (katexElement) {
            e.preventDefault();
            const cleanText = extractKaTeXText(katexElement);
            e.clipboardData.setData('text/plain', cleanText);
        }
    });

    // Log that script is active
    console.log('KaTeX Copy Handler active');
})();