Search code examples
typescriptvisual-studio-codevscode-extensionslanguage-server-protocol

How to retrieve the rootPath (or any other client side info) from language server side?


I am working on a language extention, based on the sample "language server" (https://code.visualstudio.com/docs/extensions/example-language-server).

On the server side, I need to know the current folder used by vscode, which, on the client side, would be retrieved by :

import * as vscode from 'vscode';
[...]
let curFolder : string =  vscode.workspace.rootPath;
[...]

But if I try to use this on server side,

  1. I get a TS compiler error : error TS2307: Cannot find module 'vscode'
  2. Once client is started (using F5 in client), I'm unable to attach to the server (using F5 in server).

Both my server and client package.json specify :

  "devDependencies": {
    "typescript": "^1.8.9",
    "vscode": "^0.11.12"
  }

My understanding is that the server only communicates with the client via the IConnection object, and thus does not have access to vscode.* data that are maintained on the client side.

My current work around it to use this on server side:

connection.sendRequest({ method: "getRootPath" })
.then( (rootPath : string) => {
    [...]

and this code on client side:

languageClient.onRequest({method: "getRootPath"}, (params : any) : string => {
        return vscode.workspace.rootPath;
} );

Is there any better way to do this ?


Solution

  • It's actually very simple. The rootPath is provided to the language server at initialization, in the parameters of "connection.onInitialize".

    connection.onInitialize(
    (params) : InitializeResult => {
        connection.console.log("Initialization : " + params.rootPath);
    });