Sublime Text自定义快捷键格式化选中文本方法求助
Got it, let's figure out how to set up a custom shortcut that wraps your selected text into Django's {% trans "..." %} tag—this is totally doable with editor-specific tools or cross-platform scripting. Here are step-by-step solutions for the most common setups:
VS Code makes this easy with user snippets and custom keybindings:
- Step 1: Create a custom snippet
Open the command panel (Ctrl+Shift+P), typeConfigure User Snippets, then selectNew Global Snippets file. Name it something likedjango-trans.code-snippets, then paste this:{ "Wrap selected text in trans tag": { "prefix": "trans-wrap", "body": [ "{% trans \"$TM_SELECTED_TEXT\" %}" ], "description": "Wrap selected text in Django trans template tag" } } - Step 2: Bind a shortcut
Open keyboard shortcut settings (Ctrl+K Ctrl+S), click the "Open Keyboard Shortcuts (JSON)" icon in the top-right. Add this entry (replacectrl+shift+twith your preferred shortcut):
The{ "key": "ctrl+shift+t", "command": "editor.action.insertSnippet", "args": { "name": "Wrap selected text in trans tag" }, "when": "editorTextFocus && editorHasSelection" }whencondition ensures the shortcut only works when you have text selected and the editor is active.
For Sublime users, use snippets + keybindings:
- Step 1: Create a snippet
Go toTools > Developer > New Snippet, then paste this:
Save it as<snippet> <content><![CDATA[ {% trans "${SELECTION}" %} ]]></content> <tabTrigger>trans-wrap</tabTrigger> <scope>text.html.django</scope> <description>Wrap selected text in trans tag</description> </snippet>django-trans.sublime-snippetin Sublime's User directory. - Step 2: Add a shortcut
OpenPreferences > Key Bindingsand add this:{ "keys": ["ctrl+shift+t"], "command": "insert_snippet", "args": {"name": "Packages/User/django-trans.sublime-snippet"}, "context": [{"key": "selection_empty", "operator": "equal", "operand": false}] }
If you want this shortcut to work in any editor, AutoHotkey is a great cross-platform (Windows-focused) tool:
- Install AutoHotkey, then create a new
.ahkfile with this code:
Run the script, and you can use the shortcut in any app where you can select text.^+t:: ; Ctrl+Shift+T as the shortcut Send, ^c ; Copy selected text ClipWait, 1 ; Wait for clipboard to populate if ErrorLevel return Clipboard := "{% trans """ . Clipboard . """ %}" ; Format the text Send, ^v ; Paste the formatted text back return
All these solutions directly solve your problem: select text like Home, hit your custom shortcut, and it becomes {% trans "Home" %}. For other editors (like IntelliJ/PyCharm), the core idea is the same—use the editor's snippet/macro system to wrap selected text and bind it to a shortcut.
内容的提问来源于stack exchange,提问作者CodeUnsolved

