如何在VSCode中对选中文本运行自定义JS代码生成Markdown目录?
Here are a couple of straightforward solutions to automate converting selected text into markdown anchor links (like #chapter-one) and copy them to your clipboard, with optional keyboard shortcuts:
Solution 1: Quick Snippet for Direct Link Insertion (No Extensions)
If you want to insert the full markdown link directly into your document instead of just copying the anchor:
- Open user snippets: Press
Ctrl+Shift+P(Windows/Linux) orCmd+Shift+P(Mac), search for Configure User Snippets, then selectmarkdown.json(or create a global snippet file for cross-language use). - Paste this snippet into the file:
"Create Markdown Anchor Link": { "prefix": "anchor-link", "body": [ "* [${TM_SELECTED_TEXT}](#${TM_SELECTED_TEXT/(.*)/${1:/downcase}/}${TM_SELECTED_TEXT/ /-/g})" ], "description": "Generate formatted markdown anchor link from selected text" }
- How to use:
- Select your heading text (e.g., "Chapter One")
- Press
Ctrl+Shift+P, search for Insert Snippet, then pick "Create Markdown Anchor Link" - The full link
* [Chapter One](#chapter-one)will appear at your cursor.
Solution 2: Copy Anchor to Clipboard (With Custom Shortcut)
If you specifically need to copy just the anchor fragment (like #chapter-two) to your clipboard, use this extension-based method for maximum flexibility:
Step 1: Install the Custom JavaScript Commands Extension
Search for it in the VSCode Marketplace and install it—it’s lightweight and lets you run custom JS code directly in VSCode.
Step 2: Add Your Anchor Generation Command
- Open the extension settings: Press
Ctrl+Shift+P, search for Custom JavaScript Commands: Open Settings. - Add this command to the
customJavaScriptCommands.commandsarray:
{ "name": "Copy Anchor to Clipboard", "command": "const editor = vscode.window.activeTextEditor; if (editor) { const selectedText = editor.document.getText(editor.selection); const anchor = '#' + selectedText.toLocaleLowerCase().split(' ').join('-'); vscode.env.clipboard.writeText(anchor); vscode.window.showInformationMessage(`Anchor copied: ${anchor}`); }" }
Step 3: Bind a Keyboard Shortcut
- Open keyboard shortcuts: Press
Ctrl+K Ctrl+S(Windows/Linux) orCmd+K Cmd+S(Mac). - Search for the command name you just added: Copy Anchor to Clipboard.
- Click the pencil icon to assign a shortcut (I recommend
Ctrl+Alt+AorCmd+Alt+Afor easy access).
How to Use:
- Select any text in your editor
- Hit your custom shortcut
- The formatted anchor will be copied to your clipboard, and a small confirmation pop-up will appear.
Alternative: No-Extension Python Script (For Purists)
If you’d rather avoid extensions, use a simple Python script and VSCode tasks:
- Create a
generate_anchor.pyfile in your workspace:
import sys import pyperclip if len(sys.argv) > 1: text = sys.argv[1] anchor = '#' + text.lower().replace(' ', '-') pyperclip.copy(anchor) print(f"Successfully copied: {anchor}")
- Install the required package: Run
pip install pyperclipin your terminal. - Create a
.vscode/tasks.jsonfile:
{ "version": "2.0.0", "tasks": [ { "label": "Copy Anchor", "type": "shell", "command": "python ${workspaceFolder}/generate_anchor.py '${selectedText}'", "problemMatcher": [], "runOptions": { "runOn": "folderOpen" } } ] }
- Bind this task to a shortcut (same as Step 3 in Solution 2) and you’re good to go.
内容的提问来源于stack exchange,提问作者DIRECTcut

