Search code examples
language-server-protocolclangd

Use clangd via the terminal


I would like to test clangd with my terminal but I can't make a request. I have read the documentation for the LSP language but I still don't understand how to start a connection etc.

Here is the opening message:

clangd is a language server that provides IDE-like features to editors.

It should be used via an editor plugin rather than invoked directly. For more information, see:
        https://clangd.llvm.org/
        https://microsoft.github.io/language-server-protocol/

clangd accepts flags on the commandline, and in the CLANGD_FLAGS environment variable.

I[12:27:23.132] clangd version 13.0.0 (ssh://git@git.jetbrains.team/llvm/llvm-project.git f453b8779f319ecd0e7f6f2fdd5e78ec375aaa47 based on LLVM 1d42ba254fa3203f1ad5916ed414a84312f5bba9 revision)
I[12:27:23.135] PID: 7604
I[12:27:23.136] Working directory: C:\Users\Tal\AppData\Local\JetBrains\CLion 2021.1.3\bin\clang\win
I[12:27:23.137] argv[0]: C:\Users\Tal\AppData\Local\JetBrains\CLion 2021.1.3\bin\clang\win\clangd.exe
I[12:27:23.148] Starting LSP over stdin/stdout

After that, I can't send a message.


Solution

  • You have to read https://microsoft.github.io/language-server-protocol/specifications/specification-current/#headerPart and send a message using json-rpc protocol to the stdin of the process. For example:

    send() { msg=$(jq -n "$@"); printf "%s\r\n" "Content-Length: ${#msg}" "" "$msg" | tee /dev/stderr; }
    send '{ jsonrpc: "2.0", id: 1, method: "exit" }' | clangd
    
    clangd is a language server that provides IDE-like features to editors.
    
    It should be used via an editor plugin rather than invoked directly. For more information, see:
            https://clangd.llvm.org/
            https://microsoft.github.io/language-server-protocol/
    
    clangd accepts flags on the commandline, and in the CLANGD_FLAGS environment variable.
    
    I[13:14:59.127] clangd version 13.0.1
    I[13:14:59.127] Features: linux
    I[13:14:59.127] PID: 94070
    I[13:14:59.127] Working directory: /home/kamil
    I[13:14:59.127] argv[0]: clangd
    I[13:14:59.127] Starting LSP over stdin/stdout
    Content-Length: 53
    
    {
      "jsonrpc": "2.0",
      "id": 1,
      "method": "exit"
    }
    I[13:14:59.131] <-- exit(1)
    E[13:14:59.131] Call exit before initialization.
    I[13:14:59.131] --> reply:exit(1) 0 ms, error: -32002: server not initialized
    Content-Length: 83
    
    {"error":{"code":-32002,"message":"server not initialized"},"id":1,"jsonrpc":"2.0"}I[13:14:59.131] Warning: Missing Content-Length header, or zero-length message.
    E[13:14:59.132] Transport error: Input/output error
    I[13:14:59.132] LSP finished, exiting with status 1