edo1z blog

プログラミングなどに関するブログです

Rust - WSL環境のvscodeでコードフォーマット等のショートカットキーを設定する

フォーマットに使うコマンド

rustfmtです。cargo fmt で使えるか確認してください。もし使えない場合はインストール・設定が必要だと思いますので、下記等を確認してください。

GitHub - rust-lang/rustfmt: Format Rust code

利用してるvscodeの拡張

下記を利用しています。

Rust (rls) - Visual Studio Marketplace

コマンドをタスクに登録する

vsocdeの標準機能で、Tasksとういのがあります。.vscode/tasks.json にタスクを書くと、そのタスクを簡単に実行できるようになります。ビルドやフォーマットを登録したtasks.json のサンプルが下記になります。登録したタスクは、ctrl + shift + b でタスク一覧が表示されますので、そこから選択することで、簡単に実行できます。

{
  "version": "2.0.0",
  "tasks": [
    {
      "type": "shell",
      "label": "build",
      "command": "wsl.exe",
      "args": [
        "~/.cargo/bin/cargo",
        "build"
      ],
      "problemMatcher": [
        "$rustc"
      ],
      "group": "build",
      "presentation": {
        "reveal": "silent",
        "panel": "dedicated"
      }
    },
    {
      "type": "shell",
      "label": "fmt",
      "command": "wsl.exe",
      "args": [
        "~/.cargo/bin/cargo",
        "fmt"
      ],
      "problemMatcher": [
        "$rustc"
      ],
      "group": "build",
      "presentation": {
        "reveal": "silent",
        "panel": "dedicated"
      }
    },
    {
      "type": "shell",
      "label": "run",
      "command": "wsl.exe",
      "args": [
        "~/.cargo/bin/cargo",
        "run"
      ],
      "problemMatcher": [
        "$rustc"
      ],
      "group": "build",
      "presentation": {
        "reveal": "always",
        "panel": "dedicated"
      }
    },
  ]
}

ショートカットキーに登録する

上記で登録したタスクを、キーに紐づけます。まず、ctrl + shift + P で、コマンドパレットを開き、下記のように 基本設定:キーボードショットカットを開く(json) をクリックします。

Image from Gyazo

すると、keybindings.json が開きますので、下記を追記します。

[
  {
    "key": "ctrl+alt+f",
    "command": "workbench.action.tasks.runTask",
    "args": "fmt"
  },
  {
    "key": "ctrl+alt+b",
    "command": "workbench.action.tasks.runTask",
    "args": "build"
  },
  {
    "key": "ctrl+alt+r",
    "command": "workbench.action.tasks.runTask",
    "args": "run"
  },
]

これでショートカットキーの設定ができます。上記の args には、tasks.json で設定した label の値を設定します。