Ctrl+L Markdown Link Wrapper

Wrap selected text in markdown link format [text]() and place cursor between parentheses

目前为 2024-10-13 提交的版本。查看 最新版本

// ==UserScript==
// @name         Ctrl+L Markdown Link Wrapper
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  Wrap selected text in markdown link format [text]() and place cursor between parentheses
// @author       minnie
// @match        https://*.reddit.com/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // Listen for Ctrl+L keypress
    document.addEventListener('keydown', function(e) {
        if (e.ctrlKey && e.key.toLowerCase() === 'l') {
            e.preventDefault();

            // Get the focused element (typically the textarea)
            let activeElement = document.activeElement;

            // Check if the focused element is a textarea within a .usertext-edit container
            if (activeElement && activeElement.tagName.toLowerCase() === 'textarea' && activeElement.closest('.usertext-edit')) {
                let textarea = activeElement;
                let selectionStart = textarea.selectionStart;
                let selectionEnd = textarea.selectionEnd;

                // Get the selected text
                let selectedText = textarea.value.substring(selectionStart, selectionEnd);

                // Wrap the selected text in markdown link format
                let markdownText = `[${selectedText}]()`;

                // Replace the selected text with the markdown link
                textarea.setRangeText(markdownText, selectionStart, selectionEnd, 'end');

                // Set the cursor inside the parentheses
                textarea.selectionStart = selectionStart + markdownText.length - 1;
                textarea.selectionEnd = selectionStart + markdownText.length - 1;

                // Focus back on the textarea
                textarea.focus();
            }
        }
    });
})();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址