VS Code Cheatsheet

I'm getting hooked to Visual Studio Code more and more these days ... it's light and fast! Here's my cheatsheet when using VS Code.

Frequently used (but forgotten) shortcuts

  • Copy current line up or down: Option + Shift + up/down
  • Delete current line : ⌘ + Shift + K
  • Move current line up or down: Option + up/down
  • Prettify flat JSON: Option + Shift + f
  • Show or hide sidebar: ⌘ + b
  • Quick select the language: ⌘ + k then m
  • Quick open file: ⌘ + p
  • Jumping to to other tab (if ⌘ + 1 doesn't work): ctrl + tab or ctrl + shift + tab

To see all of the keybindings, ⌘ + k then s

Official PDF poster here.

Adding Fix on Save

Pre-requisites, install these extensions:

  1. Eslint. This extension will try to use the local eslint library in the local project folder otherwise, it will use the global.
  2. Prettier
  3. Prettier Eslint

Given that the project already has .eslintrc or .eslintrc.json rules configured, add this to settings.json

In some cases, I also still need to configure Prettier settings such as the single quote, no semicolon needed, etc.

"editor.codeActionsOnSave": {
    "source.fixAll": true
  },
"eslint.alwaysShowStatus": true,
"eslint.validate": ["javascript", "javascriptreact", "typescript"],
"editor.defaultFormatter": "esbenp.prettier-vscode",
"[javascript]": {
  "editor.defaultFormatter": "esbenp.prettier-vscode"
},

When combined with Surround extension (more details below), here's what it looks like.

Screenflick Movie 6.gif

Here's a good reference article by DigitalOcean: https://www.digitalocean.com/community/tutorials/workflow-auto-eslinting.

Useful extensions

Sort Lines

When you have lines to sort, simply hit F9 (Fn + F9, in my case...) for default ascending sort or open the command panel (⌘+shift+p) and type sort.

Screenshot 2021-07-30 at 10.00.41 PM.png

Gitlens

Shows who modified that line of code and possibly ... get a better idea from her or his commit message.

Screenshot 2021-07-30 at 10.06.09 PM.png

Surround.

Gives you the ability to wrap things quickly. By using Cmd+Shift+T (see the gif above).

I can also customise it with any kind of surrounding character. For example, here's the settings to add single and double quote:

"surround.custom": {
    "surround.with.singleQuote": {
      "label": "Wrap with single quote",
      "description": "\\'...\\'",
      "snippet": "'$TM_SELECTED_TEXT'$0",
      "languageIds": [
        "html",
        "javascript",
        "javascriptreact",
        "typescript",
        "markdown",
        "plaintext"
      ]
    },
    "surround.with.doubleQuote": {
      "label": "Wrap with double quote",
      "description": "\"...\"",
      "snippet": "\"$TM_SELECTED_TEXT\"$0",
      "languageIds": [
        "html",
        "javascript",
        "javascriptreact",
        "typescript",
        "markdown",
        "plaintext"
      ]
    }
  },

My favorite theme and icon

I'm using Bearded Theme Arc Eolstorm, Eggplant, Anthracite color themes feels good!

Plus, Material Icon.

Color customisation

This is actually the most fun part for me as it's really comes down on the personal taste level. The colors here applied to mostly the tree (file tree) or list (search list).

"list.hoverBackground": "#e96f2d" -> Orange. This is for any thing the mouse hover.

"list.activeSelectionBackground": "#9f9ac4" -> Bluish gray. Whenever I search for something, the system usually preselect an item. This is the background color.

"list.highlightForeground": "#ff0000" -> Red and "list.activeSelectionForeground": "#62ff00" -> Green When I start typing characters, the filenames that matches will be highlighted with this color, while the remaining "preselected" filename's characters will be highlighted with activeSelectionForeground

Here's the visual helper

Screenshot 2021-07-30 at 9.29.05 PM.png

"list.inactiveSelectionBackground" -> Dark green. When a file is being edited, the tree will usually auto select that file, and is theoretically in inactive selected state. It will be highlighted with this color.

There are many other aspects that can be customized, the complete references is here

Disable preview

By default, when you click any file from the file tree, it will open a tab. If you don't modify that file, VSCode will replace it with the next file that you click. However, I want VSCode not to close files that I clicked.

Hit ⌘ + ,, type enablePreview. Uncheck the Workbench > Editor: Enable Preview.

vscode-disable-preview.png

Howtos

I came across some ways dealing with strings other than cut&paste or find and replace!

Multiple selection and replace

How to replace all parseFloat to parseInt in one go?

const payload = {
  t: values.t ? parseFloat(values.t) : 0,
  a: parseFloat(values.a),
  b: parseFloat(values.b),
  c: parseFloat(values.c),
  d: parseFloat(values.d),
  e: parseFloat(values.e),
  f: parseFloat(values.f),
  g: parseFloat(values.g),
  h: parseFloat(values.h)
}
  1. Select parseFloat
  2. ⌘ + d will select other matching string. ⌘ + d again to select the next matching string
  3. Start typing parseInt

vscode-multiple-select.gif

String processing using regex

Single line selection

Let's say I have these lines. In Swift context, these are a dictionary of an enum as the key and String value. I needed to transform these into [.header, .responseText, .merchantNameAddress,...], and I didn't want to repeat typing the enum cases.

.header: "HEADER",
.responseText: "02",
.merchantNameAddress: "D0",
.transactionDate: "03",
.transactionTime: "04",
.stan: "H6",
.terminalId: "16",
.merchantId: "D1",

I can select each line by pressing shortcut to find (⌘+f), activate the regex icon .* or by pressing (⌘ + option + r) and type ^(.+)$. Once again, make sure the Regex button is selected.

In this case, ^(.+)$ is the regex to select the entire line, and anything selected is put into variable $1.

Thing is, I just want the case name with dot e.g. .merchantId. How can I remove the trailing? I'll go over Regex101, copy paste a sample line .merchantId: "D1", and play around!

First, I got (:\s\"\w+\",) to select everything beginning from : to the ,.

But I realise that I still need the comma, so I ended up using (:\s\"\w+\"). This will select : "HEADER", from .header: "HEADER", so that I can remove it from each line.

So, hit ⌘+f , enter the regex and click the Replace All button.

vscode-find-regex.png

In case I want to add : for each line again, I can select each line with ^(.+)$, and replace it with $1:! Magic!

Multi line selection

Let's say I have a long JSON text. I want to search only this particular object with key partnerName and replace the entire value of type from null to null, string.

"partnerName": {
  "type": "null"
},

I could use this regex (partnerName".*\n\s*"type":\s*)"null" and replace with $1"string, null"

If the partnerName value is string and I need to change the regex to (partnerName".*\n\s*"type":\s*)"string".

Yep, I should credit to Mark, the guy who answered my question on Stackoverflow.

That long json looks like this:

{
  "type": "object",
  "properties": {
    "node": {
      "type": "object",
      "properties": {
        "id": {
          "type": "string"
        },
        "name": {
          "type": "string"
        },
        "description": {
          "type": "string"
        },
        "type": {
          "type": "string"
        },
        "frequency": {
          "type": "string"
        },
        "maxCount": {
          "type": "integer"
        },
        "points": {
          "type": "integer"
        },
        "startAt": {
          "type": "string"
        },
        "endAt": {
          "type": "string"
        },
        "partnerName": {
          "type": "null"
        },
        "action": {
          "type": "null"
        }
      },
      "required": [
        "id",
        "name",
        "description",
        "type",
        "frequency",
        "maxCount",
        "points",
        "startAt",
        "endAt",
        "partnerName",
        "action"
      ]
    }
  },
  "required": [
    "node"
  ]
},

Final configuration

Here's my complete settings.json

{
  "editor.tabSize": 2,
  "editor.minimap.enabled": false,
  "editor.maxTokenizationLineLength": 30000,
  "editor.formatOnSave": true,
  "editor.formatOnType": true,
  "editor.formatOnPaste": true,
  "editor.wordWrap": "on",
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  "eslint.alwaysShowStatus": true,
  "eslint.validate": ["javascript", "javascriptreact"],
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "window.zoomLevel": 1,
  "workbench.editor.enablePreview": false,
  "workbench.colorTheme": "Bearded Theme Arc Eggplant",
  "workbench.colorCustomizations": {
    "list.hoverBackground": "#e96f2d",
    "list.activeSelectionBackground": "#9f9ac4",
    "list.highlightForeground": "#ff0000",
    "list.activeSelectionForeground": "#62ff00",
    "list.inactiveSelectionBackground": "#0e474d"
  },
  "emmet.triggerExpansionOnTab": true,
  "javascript.format.insertSpaceAfterConstructor": true,
  "javascript.format.insertSpaceBeforeFunctionParenthesis": true,
  "workbench.iconTheme": "material-icon-theme",
  "surround.custom": {
    "surround.with.singleQuote": {
      "label": "Wrap with single quote",
      "description": "\\'...\\'",
      "snippet": "'$TM_SELECTED_TEXT'$0",
      "languageIds": [
        "html",
        "javascript",
        "javascriptreact",
        "typescript",
        "markdown",
        "plaintext"
      ]
    },
    "surround.with.doubleQuote": {
      "label": "Wrap with double quote",
      "description": "\"...\"",
      "snippet": "\"$TM_SELECTED_TEXT\"$0",
      "languageIds": [
        "html",
        "javascript",
        "javascriptreact",
        "typescript",
        "markdown",
        "plaintext"
      ]
    }
  },
  "security.workspace.trust.untrustedFiles": "open",
  "material-icon-theme.files.associations": {},
  "prettier.singleQuote": true,
  "eslint.packageManager": "yarn",
  "prettier.semi": false,
  "prettier.trailingComma": "none"
}

Alright, hope you learn something new!