如何配置WebStorm以避免复制空白内容或空行?
I feel your pain—accidentally overwriting your clipboard with an empty line when you meant to paste is such a frustrating slip-up! Luckily, WebStorm gives you the tools to fix this behavior. Here's how to set up a "smart copy" action that only copies content if the current line isn't empty or just whitespace:
Step 1: Create a Custom Macro with a Conditional Script
We’ll build a macro that checks if the current line has actual content before copying:
- Open the macro recorder: Go to
Edit > Macros > Start Macro Recording. - Press
Ctrl+Shift+A(Find Action) and search for Run Groovy Script—select this action. - Paste the following script into the pop-up dialog (it checks if the line has non-whitespace content before triggering a copy):
def editor = com.intellij.openapi.editor.EditorFactory.instance.currentEditor def document = editor.document def caretPos = editor.caretModel.logicalPosition def lineStart = document.getLineStartOffset(caretPos.line) def lineEnd = document.getLineEndOffset(caretPos.line) def lineText = document.getText(com.intellij.openapi.util.TextRange.create(lineStart, lineEnd)) if (!lineText.trim().isEmpty()) { def copyAction = com.intellij.openapi.actionSystem.ActionManager.instance.getAction("EditorCopy") copyAction.actionPerformed(com.intellij.openapi.actionSystem.AnActionEvent.createFromDataContext("", null, com.intellij.openapi.actionSystem.DataContext.EMPTY_CONTEXT)) } - Click OK to run the script, then stop recording the macro and name it something like
Smart Copy Non-Empty Line.
Step 2: Assign the Macro to Ctrl+C
Now replace the default copy shortcut with our smart macro:
- Open
File > Settings > Keymap(or pressCtrl+Alt+S). - Search for the macro you just created (
Smart Copy Non-Empty Line). - Right-click it and select Add Keyboard Shortcut.
- Press
Ctrl+Cin the shortcut dialog. WebStorm will warn you this shortcut is already used for the defaultCopyaction—choose Remove to unassign the default action and assign it to your macro. - Click OK to save your changes.
Alternative: Use a Plugin (Simpler Option)
If writing a script feels too technical, head to the WebStorm Plugin Marketplace and search for terms like "smart copy" or "prevent empty copy". These plugins add pre-built functionality to skip copying empty/whitespace-only lines when you press Ctrl+C without a selection.
Now, when you press Ctrl+C on an empty line (or one with only spaces/tabs), nothing gets copied—your clipboard will stay safe with the content you intended to keep!
内容的提问来源于stack exchange,提问作者Sandeep Gupta

