visual-studio-codevscode-keybinding

VS Code hotkey for putting a semicolon at the end a line in VS Code


Currently it's a small pain to do End,;,Enter when I need to put a semicolon at the end of a line when the cursor is somewhere in the middle. The optimal in my opinion would be to do Ctrl+; to put a semicolon at the end of the current line and immediately after press Ctrl+Enter as it would be language agnostic.

Any way I could achieve this functionality? Improvements to the workflow are also welcome.


Solution

  • I'm sure you could cook something up with runCommands. Ex. (in keybindings.json, which you open with Preferences: Open Keyboard Shortcuts (JSON) in the command palette):

    {
        "key": "", // TODO
        "command": "runCommands",
        "args": {
            "commands": [
                "cursorEnd",
                { "command": "type", "args": {"text": ";"} },
                // TODO (optional) now take your pick from the following:
                // "lineBreakInsert",               // inserts new line without moving cursor to new line
                // "editor.action.insertLineAfter", // inserts new line after current line regardless of where cursor is in current line, and moves cursor to the start of the new line
            ],
        },
    },
    

    I wish cursorUndo or workbench.action.navigateBackInEditLocations could be used to move the cursor back to the pre-move-to-end position, but sadly, no (typing kills the cursor history). But courtesy of Mark in the comments, if you want to return to the starting cursor position, you can use this trick:

    {
        "key": "ctrl+b", // TODO
        "command": "runCommands",
        "args": {
            "commands": [
                "editor.action.setSelectionAnchor",
                "cursorEnd",
                { "command": "type", "args": {"text": ";"} },
                "editor.action.goToSelectionAnchor",
                "editor.action.cancelSelectionAnchor",
            ],
        },
    },