❄️

VSCodeでNixOS Modulesの補完を手にいれる

に公開

概要


Nix言語の言語サーバーであるnixdには、モジュールシステムoptionsに相当するNix式を設定することで、オプションを補完候補に追加する機能があります。
https://github.com/nix-community/nixd

VSCode側にNix IDE拡張機能をインストールして適切な設定をすることで、VSCodeで.nixファイルを開いたときにnixdを起動し、言語サーバーとして使用してくれるようになります。
https://github.com/nix-community/vscode-nix-ide

補完機能のほか、インレイヒントでnixpkgsパッケージのバージョンが表示されたり、linterが警告を出してきたりします。

設定手順

エディターごとのセットアップ方法はドキュメントがnixdの公式リポジトリに存在するので、随時参照してください。
https://github.com/nix-community/nixd/blob/main/nixd/docs/editor-setup.md

本稿ではVSCodeでのセットアップ手順を解説します。

nixdのインストール

任意の方法でnixdをインストールします。

# home-managerの場合
home.packages = with pkgs; [
   nixd
];

もしくは、後述の設定を終えた上で.nixファイルを開くことで、拡張機能の機能でnixdをインストールさせることもできるようです。

Nix IDE拡張機能のインストール

インストールしてください。
https://marketplace.visualstudio.com/items?itemName=jnoortheen.nix-ide

settings.jsonの設定

必須な設定項目はこんな感じです。

  "nix.enableLanguageServer": true,
  "nix.serverPath": "nixd",
  "nix.serverSettings": {
    "nixd": {
      "options": {
        "nixos": {
          "expr": "(builtins.getFlake \"${workspaceFolder}\").nixosConfigurations.ホスト名.options"
        }
      }
    }
  }
設定値 説明
nix.enableLanguageServer true
nix.serverPath nixdの実行パスを指定する
nix.serverSettings.nixd.options 後述

補完設定の書き方

settings.jsonのnix.serverSettings.nixd.optionsに補完候補の設定を記載します。
スキーマはこんな感じです。

"options": {
    "任意の名前": {
        "expr": "optionsのnix式"
    }
}

nix式は評価するとoptionsのattribute setが得られるものを設定します。

記述例

このようにするとVSCodeでNixOSのdotfilesを開いた時にNixOS Modulesが補完候補に現れるようになります。

"expr": "(builtins.getFlake \"${workspaceFolder}\").nixosConfigurations.ホスト名.options"

REPLで評価して確認すると良いでしょう。

~
❯ nix repl
Nix 2.26.2
Type :? for help.
nix-repl> (builtins.getFlake "/Users/hikuo/ghq/github.com/hikuohiku/dots-nix").nixosConfigurations.hikuo-desktop.options
{
  _module = { ... };
  appstream = { ... };
  assertions = { ... };
    ...
  warnings = { ... };
  xdg = { ... };
  zramSwap = { ... };
}

NixOS Modulesの他にもhome-manager, nix-darwinやflake-partsのオプションなども同じ要領で追加することができます。

nixdの公式リポジトリにもいくつか例があります。
https://github.com/nix-community/nixd/blob/main/nixd/docs/configuration.md#options-options

最後に僕の設定例も置いておきます。参考にしてください。
https://github.com/hikuohiku/dots-nix/blob/369031de9e2ac7c3e785478b6119b26858a2b36b/.vscode/settings.json

Discussion