Blog Post
VSCode Snippet: console.log on a Hotkey
How I set up Cmd+Shift+L in VSCode to instantly insert console.log() — or console.log('varName', varName) when a variable is selected.
I used to rely on a VSCode extension for this. At some point I decided to remove it and write my own keybinding instead. Turns out it only takes a few lines of JSON.
- Press it with nothing selected → inserts
console.log()with the cursor inside - Press it with a variable selected → inserts
console.log('variableName', variableName)on the next line
The Setup
Open the Command Palette with Cmd+Shift+P, search for Open Keyboard Shortcuts (JSON), and add these two entries:
[ { "key": "cmd+shift+l", "command": "editor.action.insertSnippet", "when": "editorTextFocus && !editorHasSelection", "args": { "snippet": "console.log($1)$0" } }, { "key": "cmd+shift+l", "command": "runCommands", "when": "editorTextFocus && editorHasSelection", "args": { "commands": [ "editor.action.clipboardCopyAction", "cursorLineEnd", { "command": "editor.action.insertSnippet", "args": { "snippet": "\nconsole.log('$CLIPBOARD', $CLIPBOARD)$0" } } ] } }]On Windows or Linux, replace cmd with ctrl.
How It Works
The two when conditions — editorHasSelection and !editorHasSelection — make sure the right variant fires.
When no text is selected, a simple snippet inserts console.log() and places the cursor inside the parentheses.
When a variable is selected, three commands run in sequence:
clipboardCopyAction— copies the selected textcursorLineEnd— moves the cursor to the end of the line, clearing the selectioninsertSnippet— inserts the log statement on a new line, reading the variable name from$CLIPBOARD
So selecting DEVICE_NAME and pressing the hotkey gives:
const DEVICE_NAME = 'GlucoKeto-Monitor'console.log('DEVICE_NAME', DEVICE_NAME)No extensions needed. runCommands is built into VSCode.