clangclang-format

how to invoke clangd to format a file


I have a workable version of clangd in my bin, but there is no clang-format. I want to format a file from command line, how to do this?

In clangd doc, it says

clangd embeds clang-format

A standalone clang-format can directly format a file from command line. I don't know whether clangd can do the same.


Solution

  • Although, the docs say clangd embeds clang-format, there is no actual clang-format binary inside clangd (at least that's what I gather from reading its source). The term "embeds" probably refers to shared source, because clangd's Format.h has an #include clang/Format/Format.h statement, which includes clang's formatting functions from clang/include/clang/Format/Format.h.

    The clangd Readme states it the way I understand it:

    clangd is a language server, and provides C++ IDE features to editors.

    The clangd binary only implements an LSP server, which returns the necessary formatting changes, when queried by a client (e.g. VSCode). However, the LSP client still needs to apply the formatting changes. This matches with the observation you made in the comments of VSCode sending the JSON RPC and clangd returning a list of changes. Thus, you need some program that can act as an LSP client. You could write something yourself and it would teach a lot about LSP (reading Spec is helpful). However, if working in a team distributing your home cooked software is the actual pain. I recommend going with existing implementations.

    If you have python available, use pipx to install the python version of clang-format. No admin rights are needed for installation. With pipx ensurepath you make the installed programs available in your PATH.

    python3 -m pip install --user pipx
    python3 -m pipx ensurepath
    pipx install clang-format
    

    Alternatively, you could use VSCode clangd extension and format from inside VSCode.

    There's a built-in LSP client in Neovim as well. Neovim has the advantage that you can easily run its commands from the terminal, if you need a hack for scripting things.