Jump to content

Visual Studio Code: Difference between revisions

m
Fix typo.
imported>Edrex
(Add instructions for installing insiders build)
m (Fix typo.)
 
(26 intermediate revisions by 14 users not shown)
Line 1: Line 1:
{{note|Visual Studio Code is [[FAQ/unfree|unfree]], its license prohibits distribution. See the [[FAQ/unfree]] page to install unfree software.}}
{{note|Visual Studio Code is [[FAQ/unfree|unfree]], its license prohibits distribution. See the [[FAQ/unfree]] page to install unfree software.}}


For the free distribution of the vscode codebase (without MS branding/telemetry) see [[VSCodium]].
Visual Studio Code is a cross-platform text editor developed by Microsoft, built on the Electron framework.


== Installing Microsoft's Visual Studio Code ==
For the free distribution of the VS Code codebase (without MS branding/telemetry) see [[VSCodium]].


=== With Home Manager ===
== Installation ==


If you are using [[Home Manager]], you will want to modify your <code>home.nix</code> (or a file inherited by it). Example:
=== NixOS ===


{{file|~/home.nix|nix|<nowiki>
<syntaxHighlight lang=nix>
{ config, pkgs, ... }:
environment.systemPackages = with pkgs; [ vscode ];
{
</syntaxHighlight>
  programs.home-manager.enable = true;
 
  ...    # More of your home-manager config
Extensions can be managed using the 'vscode-with-extensions' package:
 
<syntaxHighlight lang=nix>
environment.systemPackages = with pkgs; [
  (vscode-with-extensions.override {
    vscodeExtensions = with vscode-extensions; [
      bbenoist.nix
      ms-python.python
      ms-azuretools.vscode-docker
      ms-vscode-remote.remote-ssh
    ] ++ pkgs.vscode-utils.extensionsFromVscodeMarketplace [
      {
        name = "remote-ssh-edit";
        publisher = "ms-vscode-remote";
        version = "0.47.2";
        sha256 = "1hp6gjh4xp2m1xlm1jsdzxw9d8frkiidhph6nvl24d0h8z34w49g";
      }
    ];
  })
];
</syntaxHighlight>


  programs = {
Some examples here: [https://github.com/search?q=extensionFromVscodeMarketplace&type=code GitHub search for "extensionFromVscodeMarketplace"]
    ...    # Start of your programs config


    vscode = {
Note: For fetching the sha256 string you can use the following command. Make sure to replace the author, the package name and version!<syntaxhighlight lang="bash">
      enable = true;
nix-prefetch-url https://marketplace.visualstudio.com/_apis/public/gallery/publishers/ms-vscode-remote/vsextensions/remote-ssh-edit/0.47.2/vspackage
      package = pkgs.vscodium;    # You can skip this if you want to use the unfree version
</syntaxhighlight>{{ic|extensionsFromVscodeMarketplace}} is a manual way to fetch extensions. However, to keep updated from upstream, [https://github.com/nix-community/nix-vscode-extensions nix-community/nix-vscode-extensions] provides the Nix expressions for the majority of available extensions from Open VSX and VSCode Marketplace. A GitHub Action updates the extensions daily.
      extensions = with pkgs.vscode-extensions; [
        # Some example extensions...
        dracula-theme.theme-dracula
        vscodevim.vim
        yzhang.markdown-all-in-one
      ];
    }


    ...    # Rest of your programs config
It's also possible to install VS Code via [[Home Manager]]:
  }


   ...   # Rest of your home-manager config
<syntaxhighlight lang="nix">
}
programs.vscode = {
</nowiki>}}
  enable = true;
   extensions = with pkgs.vscode-extensions; [
    dracula-theme.theme-dracula
    vscodevim.vim
    yzhang.markdown-all-in-one
  ];
};
</syntaxhighlight>


* See for more options: [https://nix-community.github.io/home-manager/options.html#opt-programs.vscode.enable Home Manager Manual: Options - programs.vscode]
* See for more options: [https://nix-community.github.io/home-manager/options.html#opt-programs.vscode.enable Home Manager Manual: Options - programs.vscode]
* Search for extensions with configurations: [https://search.nixos.org/packages?channel=unstable&from=0&size=30&sort=relevance&type=packages&query=vscode-extensions NixOS Search: vscode-extensions]
* Search for extensions with configurations: [https://search.nixos.org/packages?type=packages&query=vscode-extensions NixOS Search: vscode-extensions]
 
=== Non-NixOS ===
 
<syntaxHighlight lang="console">
$ nix-env -iA nixos.vscode
</syntaxHighlight>
 
=== Use VS Code extensions without additional configuration ===
 
With the package vscode.fhs, the editor launches inside a [https://en.wikipedia.org/wiki/Filesystem_Hierarchy_Standard FHS] compliant chroot environment using buildFHSUserEnv. This reintroduces directories such as /bin, /lib, and /usr, which allows for extensions which ship pre-compiled binaries to work with little to no additional nixification.
 
{{note|From a philosophical view, use of buildFHSUserEnv allows for ease-of-use at the cost of some impurity and non-reproducibility. If you prioritize purely-declarative configurations, please stay with the above guidance.}}
 
Example usage:
<syntaxHighlight lang=nix>
environment.systemPackages = with pkgs; [ vscode.fhs ];
</syntaxHighlight>
 
Home-manager:
<syntaxHighlight lang=nix>
programs.vscode = {
  enable = true;
  package = pkgs.vscode.fhs;
};
</syntaxHighlight>
 
Adding extension-specific dependencies, these will be added to the FHS environment:
<syntaxHighlight lang=nix>
# needed for rust lang server and rust-analyzer extension
programs.vscode.package = pkgs.vscode.fhsWithPackages (ps: with ps; [ rustup zlib openssl.dev pkg-config ]);
</syntaxHighlight>


=== Insiders Build ===
=== Insiders Build ===


If you need to test a recent code change, you can run the insiders build. It is designed to run alongside the main build, with a separate <code>code-insiders</code> command and a different config path, so you can leave your main VSCode instance installed/running.
If you need to test a recent code change, you can run the insiders build. It is designed to run alongside the main build, with a separate <code>code-insiders</code> command and a different config path, so you can leave your main VS Code instance installed/running.


The following derivation [https://discourse.nixos.org/t/how-to-install-latest-vscode-insiders/7895/4 thanks to @jnoortheen], which you can add to <code>home.packages</code> (HM), <code>environment.systemPackages</code> (NixOS), etc, builds a package with the latest insiders.
The following derivation [https://discourse.nixos.org/t/how-to-install-latest-vscode-insiders/7895/4 thanks to @jnoortheen], which you can add to <code>home.packages</code> (HM), <code>environment.systemPackages</code> (NixOS), etc., builds a package with the latest insiders.


<syntaxHighlight lang=nix>
<syntaxHighlight lang=nix>
    (pkgs.vscode.override{ isInsiders = true; }).overrideAttrs (oldAttrs: rec {
(pkgs.vscode.override { isInsiders = true; }).overrideAttrs (oldAttrs: rec {
      src = (builtins.fetchTarball {
  src = (builtins.fetchTarball {
        url = "https://update.code.visualstudio.com/latest/linux-x64/insider";
    url = "https://code.visualstudio.com/sha/download?build=insider&os=linux-x64";
        sha256 = "1dajhfsdr55mfnj12clf5apy1d4swr71d3rfwlq2hvvmpxvxsa59";
    sha256 = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
      });
  });
      version = "latest";
  version = "latest";
    });
 
  buildInputs = oldAttrs.buildInputs ++ [ pkgs.krb5 ];
});
</syntaxHighlight>
</syntaxHighlight>


You will need to update the <code>sha256</code> value for each new insiders build. The new value will appear in a validation error when you try to build.


=== With nix-env ===
==== Updating insiders placeholder <code>sha256</code>: ====
 
You will need to update the placeholder <code>sha256</code> value for each new Insiders build.
 
The new value will appear in a validation error when you try to build.
 
Put an arbitrary placeholder value in the <code>sha256</code> field, try to build and you'll get an error message regarding the sha256 value.
 
 
===== If insiders error contains <code>sha256:</code>, follow these instructions:  =====
 
<pre>
//-- ...
      error: hash mismatch in file downloaded from 'https://code.visualstudio.com/sha/download?build=insider&os=linux-x64':
        specified: sha256:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
        got:      sha256:16fzxqs6ql4p2apq9aw7l10h4ag1r7jwlfvknk5rd2zmkscwhn6z
//-- ...
</pre>


Because it is NixOS, you don't have to be root in order to be able to install stuff. As a normal user, do:
Take that last line and input it where your placeholder was, 'sha256:' in the beginning should be removed.


<syntaxHighlight lang=console>
 
$ nix-env -iA nixos.vscode
===== If insiders error contains <code>sha256-</code>, follow these instructions:  =====
 
<pre>
//-- ...
        error: hash mismatch in fixed-output derivation '/nix/store/path':
        specified: sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
            got:    sha256-aQvTtZdPU2F1UjkFxiLs4A+60A4qc9bXKwKriNsCDPg=
//-- ...
</pre>
 
Take that last line and run the following python script (you can search for an online python interpreter if it's not installed), the output will give you the correct value:
 
<syntaxHighlight lang=python>
import base64
# The 'sha256-' in the beginning should be removed
text = b'aQvTtZdPU2F1UjkFxiLs4A+60A4qc9bXKwKriNsCDPg='
print(base64.decodebytes(text).hex())
</syntaxHighlight>
</syntaxHighlight>


And to open or launch the IDE, do:
Take the output from this command and input it where your placeholder was.
 
== Creating development environments using nix-shell ==
Instead of using configuration.nix to add packages (e.g. Python or NodeJS) for developing code on VSCode, you can instead use nix-shell. This will allow you to seamlessly create development environments with the correct packages for your project, without rebuilding and restarting NixOS. See [[Development_environment_with_nix-shell | this page]] for further instructions in building nix-shell development environments.
 
=== Automatically switch nix shells when switching projects ===
You can do this by using [https://github.com/nix-community/nix-direnv nix-direnv] and [https://marketplace.visualstudio.com/items?itemName=mkhl.direnv the VSCode extension direnv] for integration. View the nix-direnv github page linked for a guide on setting it up.


<syntaxHighlight lang=console>
=== Alternative for manually switching shells ===
$ code
The extension [https://marketplace.visualstudio.com/items?itemName=arrterian.nix-env-selector nix-env-selector] will make switching between different nix-shell environments within VSCode so you can switch between different coding projects easily and manually. It has a guide for setting up nix-shell environments for VSCode.
</syntaxHighlight>


== Wayland ==
== Wayland ==


If you are running Wayland, you may see a blank screen when starting vscode.
To use VS Code under Wayland, set the environment variable <code>NIXOS_OZONE_WL=1</code>:
 
To fix this, set the environment variable <code>NIXOS_OZONE_WL=1</code>:


* temporary fix: run via the terminal:  
* temporary fix: run via the terminal:  
Line 84: Line 170:
[https://github.com/NixOS/nixpkgs/commit/b2eb5f62a7fd94ab58acafec9f64e54f97c508a6 Source]
[https://github.com/NixOS/nixpkgs/commit/b2eb5f62a7fd94ab58acafec9f64e54f97c508a6 Source]


== Managing extensions ==
== Updating extension versions ==
 
Extensions can be managed using the 'vscode-with-extensions' package:
 
<syntaxHighlight lang=nix>
{ pkgs, ... }:
 
let
  extensions = (with pkgs.vscode-extensions; [
      bbenoist.nix
      ms-python.python
      ms-azuretools.vscode-docker
      ms-vscode-remote.remote-ssh
    ]) ++ pkgs.vscode-utils.extensionsFromVscodeMarketplace [{
      name = "remote-ssh-edit";
      publisher = "ms-vscode-remote";
      version = "0.47.2";
      sha256 = "1hp6gjh4xp2m1xlm1jsdzxw9d8frkiidhph6nvl24d0h8z34w49g";
  }];
  vscode-with-extensions = pkgs.vscode-with-extensions.override {
      vscodeExtensions = extensions;
    };
in {
  config = {
    environment.systemPackages = [
      vscode-with-extensions
    ];
  };
}
</syntaxHighlight>


Some useful examples here: [https://github.com/search?q=extensionFromVscodeMarketplace&type=code GitHub search for "extensionFromVscodeMarketplace"]
Nixpkgs contains a script which will run <code>code --list-extensions</code>, then look for the latest available versions of those extensions, and output a list which you can add to your Nix config in a format similar to the above. To use it, clone the [https://github.com/NixOS/nixpkgs nixpkgs repo from GitHub], and run: [https://github.com/NixOS/nixpkgs/blob/master/pkgs/applications/editors/vscode/extensions/update_installed_exts.sh nixpkgs/pkgs/applications/editors/vscode/extensions/update_installed_exts.sh]
 
=== Updating extension versions ===
 
Nixpkgs contains a script which will run <code>code --list-extensions</code>, then look for the latest available versions of those extensions, and output a list which you can add to your Nix config in a format similar to the above. To use it, clone the [https://github.com/NixOS/nixpkgs nixpkgs repo from github], and run: [https://github.com/NixOS/nixpkgs/blob/master/pkgs/applications/editors/vscode/extensions/update_installed_exts.sh nixpkgs/pkgs/applications/editors/vscode/extensions/update_installed_exts.sh]


Example output:
Example output:
Line 139: Line 192:
     sha256 = "01lc9gpqdjy6himn7jsfjrfz8xrk728c20903lxkxy5fliv232gz";
     sha256 = "01lc9gpqdjy6himn7jsfjrfz8xrk728c20903lxkxy5fliv232gz";
   }
   }
... # the output for the rest of your extensions
];
];
}%
}
</syntaxHighlight>
</syntaxHighlight>


== Remote SSH ==
== Remote SSH ==


The remote-ssh extension works by connecting to a remote host and downloading scripts and pre-built binaries to {{ic|$HOME/.vscode-server}}. When first launching remote-ssh for a NixOS host the connection will fail due to the provided node.js not having been built for a NixOS system (the dynamic libraries aren't in the same place).
The remote-ssh extension works by connecting to a remote host and downloading scripts and pre-built binaries to {{ic|$HOME/.vscode-server}}. When first launching remote-ssh for a NixOS host, the connection will fail due to the provided node.js not having been built for a NixOS system (the dynamic libraries aren't in the same place).


=== Any client to NixOS host ===
=== Any client to NixOS host ===


'''tl;dr Use [https://github.com/msteen/nixos-vscode-server nix-vscode-server] on host machines.'''
'''tl;dr Use [https://github.com/msteen/nixos-vscode-server nix-vscode-server] or [https://github.com/Mic92/nix-ld nix-ld] on host machines.'''
 
==== nix-vscode-server ====


Note that nix-vscode-server works as of 8/21/21 but is occasionally broken (See https://github.com/msteen/nixos-vscode-server/pull/3, https://github.com/msteen/nixos-vscode-server/pull/4, https://github.com/msteen/nixos-vscode-server/pull/5). Here's a workaround: Install the <code>nodejs-16_x</code> package on the NixOS host, and then run the following nix-shell script:
Note that nix-vscode-server works as of 8/21/21 but is occasionally broken (See https://github.com/msteen/nixos-vscode-server/pull/3, https://github.com/msteen/nixos-vscode-server/pull/4, https://github.com/msteen/nixos-vscode-server/pull/5). Here's a workaround: Install the <code>nodejs-16_x</code> package on the NixOS host, and then run the following nix-shell script:
Line 174: Line 228:
</syntaxHighlight>
</syntaxHighlight>


If instead you'd prefer to fix the binaries manually and have to do so every time that you upgrade your VSCode version, then you can install the <code>nodejs-16_x</code> package on the NixOS host and replace the VSCode provided version. This workaround is described here: https://github.com/microsoft/vscode-remote-release/issues/648#issuecomment-503148523. Note that nodejs needs to be updated according to VSCode upstream requirements (nodejs 16 required from 4/2022).
If instead you'd prefer to fix the binaries manually and have to do so every time that you upgrade your VS Code version, then you can install the <code>nodejs-16_x</code> package on the NixOS host and replace the VS Code provided version. This workaround is described here: https://github.com/microsoft/vscode-remote-release/issues/648#issuecomment-503148523. Note that NodeJS needs to be updated according to VS Code upstream requirements (NodeJS 16 required from 4/2022).


=== Nix-sourced VSCode to NixOS host ===
==== nix-ld ====
 
Add the following settings to <code>configuration.nix</code> on the NixOS host
 
{{file|/etc/nixos/configuration.nix|nix|<nowiki>
  programs.nix-ld.enable = true;
</nowiki>}}
 
Then run <code>nixos-rebuild switch</code> to enable <code>nix-ld</code>. Unlike the <code>nix-vscode-server</code> solution, the <code>nix-ld</code> solution also enables VSCode extensions even if they include non-Nix binaries.
 
=== Nix-sourced VS Code to NixOS host ===


If vscode-remote is installed from nix (vscode-extensions.ms-vscode-remote as above) on the client machine, everything should "just work".
If vscode-remote is installed from nix (vscode-extensions.ms-vscode-remote as above) on the client machine, everything should "just work".


== Using nix-shell ==
== Remote WSL ==
Some features of VSCode, like the Python package, require linters or other dependencies. The package [https://marketplace.visualstudio.com/items?itemName=arrterian.nix-env-selector nix-env-selector] makes this easy and does not require overrides on vscode itself to add dependencies.
 
Similar to SSH hosts, both <code>nix-vscode-server</code> and <code>nix-ld</code> solution allows a VSCode Windows client to connect a [https://github.com/nix-community/NixOS-WSL NixOS-WSL] host. However, by default the VSCode Windows client uses <code>wsl.exe --exec</code> to start the code server, which bypasses NixOS environment variables required by <code>nix-ld</code>, resulting in failures.  


== Use VSCode extensions without additional configuration ==


{{note| Only available in nixpkgs-unstable or 21.05 and after }}
As a workaround, search for the following text in all files under the directory <code>$HOME\.vscode\extensions\</code>


In [https://github.com/NixOS/nixpkgs/pull/99968 #99968], vscode-fhs and vscodium-fhs packages were added in which the editors launch inside of a [https://en.wikipedia.org/wiki/Filesystem_Hierarchy_Standard FHS] compliant chroot environment using buildFHSUserEnv. This reintroduces directories such as /bin, /lib/, and /usr, which allows for extensions which ship pre-compiled binaries to work with little to no additional nixification.
{{file|wslDaemon.js|js|<nowiki>
.push("sh","-c"
</nowiki>}}


{{note| From a philosophical view, use of buildFHSUserEnv allows for ease-of-use at the cost of some impurity and non-reproducibility. If you prioritize purely-declarative configurations, please stay with the above guidance.}}


Example usage:
Replace it with
<syntaxHighlight lang=console>
$ nix-shell -p vscode-fhs --run code
</syntaxHighlight>


Home-manager:
{{file|wslDaemon.js|js|<nowiki>
<syntaxHighlight lang=nix>
.push("sh","-l","-c"
  programs.vscode.enable = true;
</nowiki>}}
  programs.vscode.package = pkgs.vscode-fhs;
</syntaxHighlight>


Adding extension-specific dependencies, these will be added to the FHS environment:
Then restart VS Code and your VS Code client should be able to connect to NixOS host
<syntaxHighlight lang=nix>
  # needed for rust lang server extension
  programs.vscode.package = pkgs.vscode-fhsWithPackages (ps: with ps; [ rustup zlib ]);
</syntaxHighlight>


See https://github.com/nix-community/NixOS-WSL/issues/222 for the discussion about <code>wsl --exec</code> issue on NixOS-WSL.
See https://github.com/microsoft/vscode-remote-release/issues/8305#issuecomment-1661396267 about the workaround.


== Troubleshooting ==
== Troubleshooting ==
Line 219: Line 277:
</pre>
</pre>


Try to add the following setting in you system configuration (even if you don't use Gnome as desktop environment):
Try to add the following setting in your system configuration (even if you don't use Gnome as desktop environment):


{{file|/etc/nixos/configuration.nix|nix|<nowiki>
{{file|/etc/nixos/configuration.nix|nix|<nowiki>
  # needed for store VSCode auth token  
# needed for store VS Code auth token  
  services.gnome.gnome-keyring.enable = true;
services.gnome.gnome-keyring.enable = true;
</nowiki>}}
</nowiki>}}


''Optional:'' add <code>gnome.seahorse</code> to <code>environment.systemPackages</code> to install GUI for GNOME Keyring.
''Optional'': add <code>gnome.seahorse</code> to <code>environment.systemPackages</code> to install GUI for GNOME Keyring.
 
Don't forget to perform <code>nixos-rebuild switch</code> and reboot the system.
 
=== Server did not start successfully ===
 
<blockquote>
Server did not start successfully. Full server log at /home/user/.vscode-server/.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.log<br>
<br>
server log:<br>
/home/user/.vscode-server/bin/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/bin/code-server: line 12: /home/user/.vscode-server/bin/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/node: No such file or directory
</blockquote>
 
"No such file or directory" means that libc is not found, see
 
<pre>
ldd ~/.vscode-server/bin/*/node
</pre>
 
try to run the node binary on the server
 
<pre>
~/.vscode-server/bin/*/node
</pre>
 
if this fails, install node version 16, and try to patch the node binary
 
<pre>
nix-env -iA nixos.nodejs-16_x
</pre>
 
<syntaxHighlight lang=bash>
#! /bin/sh
# fix-vscode-server-node.sh
# https://github.com/microsoft/vscode-remote-release/issues/648#issuecomment-503148523
cd ~/.vscode-server/bin/*
if ! ./node -e "require('process').exit(0)"
then
  echo patching node binary $(readlink -f node)
  rm node
  ln -s $(which node)
else
  echo node is working $(readlink -f node)
fi
</syntaxHighlight>
 


Don't forget perform <code>nixos-rebuild switch</code> and reboot system.
[[Category:Applications]]
1

edit