// ==UserScript== // @name Bitcointalk Paste URL Formatter // @namespace https://bitcointalk.org/ // @version 1.3 // @description Automatically formats copy/pasted URLs as [url=URL]change_text[/url] BBCode. Press Ctrl+Shift+U to enable or disable. // @match https://bitcointalk.org/index.php?action=post* // @grant none // @author PX-Z // ==/UserScript== (function () { 'use strict'; function addStyles() { const style = document.createElement('style'); style.textContent = ` #url_formatter_note_text { padding: 3px 15px; border: 1px solid #e2cf6b; background: #fffbe4; } #url_formatter_toggle { margin-left: 8px; } `; document.head.appendChild(style); } let enabled = true; // Update the note text function updateNote() { const noteText = document.querySelector('#url_formatter_note_text'); if (!noteText) { return; } noteText.innerHTML = enabled ? 'Note: URL Formatter is ON. Press Ctrl+Shift+U to disable. Or clickDisable' : 'Note: URL Formatter is OFF. Press Ctrl+Shift+U to enable. Or clickEnable'; const toggle = document.querySelector('#url_formatter_toggle'); if (toggle) { toggle.addEventListener('click', function (e) { e.preventDefault(); enabled = !enabled; updateNote(); }); } } // Add note after #lock_warning function addNote() { const lockWarning = document.querySelector('#lock_warning'); if (!lockWarning) { return; } // Prevent duplicate note if (document.querySelector('#url_formatter_note')) { return; } const noteRow = document.createElement('tr'); noteRow.id = 'url_formatter_note'; noteRow.innerHTML = ` `; lockWarning.insertAdjacentElement('afterend', noteRow); updateNote(); } // Keyboard shortcut: Ctrl + Shift + U document.addEventListener('keydown', function (e) { if ( e.ctrlKey && e.shiftKey && e.key.toLowerCase() === 'u' ) { e.preventDefault(); enabled = !enabled; updateNote(); } }); // Handle paste document.addEventListener('paste', function (e) { // Do nothing when disabled if (!enabled) { return; } const target = e.target; // Only handle textareas if (!(target instanceof HTMLTextAreaElement)) { return; } const text = e.clipboardData.getData('text/plain').trim(); // Only process a single HTTP/HTTPS URL if (!/^https?:\/\/\S+$/i.test(text)) { return; } // Get selected text const start = target.selectionStart; const end = target.selectionEnd; const selectedText = target.value.substring(start, end); e.preventDefault(); let bbcode; if (start !== end) { // Use selected text as anchor text bbcode = `[url=${text}]${selectedText}[/url]`; } else { // No selected text bbcode = `[url=${text}]change_text[/url]`; } target.setRangeText( bbcode, start, end, 'end' ); // Notify site's JavaScript that the textarea changed target.dispatchEvent(new Event('input', { bubbles: true })); }); const observer = new MutationObserver(function () { addNote(); }); observer.observe(document.body, { childList: true, subtree: true }); // Initial check addNote(); addStyles(); })();