Code Monkey home page Code Monkey logo

lsp-clangd's Introduction

LSP-clangd

C/C++ and Objective-C/C++ support for Sublime's LSP plugin provided through clangd.

Installation

  • Install LSP and LSP-clangd from Package Control
  • (Optional) Install clangd using your package manager or let this package install clangd for you

Usage

By default, clangd will assume your code is built as clang some_file.cc, and you’ll probably get errors about missing #included files, etc.

For complex projects, clangd needs to know your build flags. This can be done using a compile_commands.json or compile_flags.txt file.

For CMake-based projects a compile_commands.json file can be generated using the -DCMAKE_EXPORT_COMPILE_COMMANDS=1 flag.

cd build
cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=1 ..
# compile_commands.json will be written to your build directory.

If your build directory is equivalent to the root of the project or <project_root>/build then clangd will find it. Otherwise, symlink or copy it to the root of your project.

See clangd Project Setup for more information on using compile_commands.json, compile_flags.txt and other build systems.

Configuration

Here are some ways to configure the package and the language server.

  • From Preferences > Package Settings > LSP > Servers > LSP-clangd

  • From the command palette: Preferences: LSP-clangd Settings

  • Project-specific configuration. From the command palette run Project: Edit Project and add your settings in:

    {
       "settings": {
          "LSP": {
             "clangd": {
                "initializationOptions": {
                  // Put your settings here eg.
                  // "clangd.header-insertion": "iwyu",
                }
             }
          }
       }
    }

Sublime Commands

Sublime Command Description
lsp_clangd_switch_source_header Switch between the main source file (.cpp) and header (.h).

lsp-clangd's People

Contributors

github-actions[bot] avatar ldap avatar predragnikolic avatar rchl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

Forkers

alien-ware

lsp-clangd's Issues

Does not recognize c++20 modules

I got a project in Sublime with CMake which produces compile_commands.json
basically main.cpp is main file, and foo.cpp is a module exported and imported and used in main.cpp

all compiles OK with GCC and LSP works but shows:
clang(module_not_found) on "import foo;" in main.cpp

here is the compile_commands.json

[
{
  "directory": "/home/r2com/projects/prog/cpp/build",
  "command": "/usr/bin/c++    -std=c++2b -fmodules-ts -std=c++23 -o CMakeFiles/hello.dir/main.cpp.o -c /home/r2com/projects/prog/cpp/src/main.cpp",
  "file": "/home/r2com/projects/prog/cpp/src/main.cpp"
},
{
  "directory": "/home/r2com/projects/prog/cpp/build",
  "command": "/usr/bin/c++    -std=c++2b -fmodules-ts -std=c++23 -o CMakeFiles/hello.dir/foo.cpp.o -c /home/r2com/projects/prog/cpp/src/foo.cpp",
  "file": "/home/r2com/projects/prog/cpp/src/foo.cpp"
}
]

and here is Cmake:

cmake_minimum_required(VERSION 3.25)
project(std_module_example CXX)

# Default to C++ extensions being off. Clang's modules support has trouble
# with extensions right now and it is not required for any other compiler
set(CMAKE_CXX_EXTENSIONS OFF)

# Set the C++ standard to C++20
set(CMAKE_CXX_STANDARD 23)

# Enable C++ modules by setting the appropriate compiler flag
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++2b")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fmodules-ts")

# Create the foo module
add_library(foo MODULE foo.cpp)

# Create an interface library for the foo module
add_library(foo_interface INTERFACE)
target_link_libraries(foo_interface INTERFACE foo)

set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
# Create the hello executable
add_executable(hello main.cpp foo.cpp)  # <-- Include foo.cpp here

# Link the foo_interface to the hello executable
target_link_libraries(hello PRIVATE foo_interface)

# Set the RPATH for the hello executable when building
set_target_properties(hello PROPERTIES
    BUILD_RPATH "$ORIGIN"
)

why LSP-Clangd cannot figure it out?

Using MSYS2's clangd

I installed clangd in MSYS2 but I can't use it with this plugin.
It'll be great if the plugin also supports usage via MSYS2.

My command:

"command": ["C:/msys64/msys2_shell.cmd", "-defterm", "-here", "-no-start", "-mingw64", "-c", "clangd"],

Unhelpful return type decoding in tooltip

When hovering over a function identifier in a C source file, the tooltip will sometimes decode the typedefs of a return type and NOT show the declared type:
Screenshot 2023-09-11 143734
(LSP is able to find the definition with no problems, where it is declared as size_t, not unsigned long long)

In other cases, it shows (in this function I declared) both the declared type and the decoded typedef:
Screenshot 2023-09-11 143908

When I'm looking up a declaration of a function, I'd like to see the declared type, rather than the typedef that's specific for my system.
I think it should work as shown in the second screenshot.

C++ popup is formatted poorly in Sublime Text

Sublime Text shows a popup that is poorly formatted given the following C++ member variable declaration:

ns_event_t *m_eventMsg{nullptr};

The syntax above is C++11 and is (nearly) equivalent to m_eventMsg = nullptr;. Sublime shows that initialization but with extra line breaks… it thinks that it’s a block.

78c18219e01e19756deb0c9f165167b7f0348c81

I think this data comes from clangd via LSP.

Link highlight style setting stopped working recently

Hello!

I'm trying to figure whether I've done something wrong, if my theme is doing something wrong, or whether a recent version of LSP-clangd has a refression.
I prefer not to have all my include statements underlined, and "link_highlight_style": "none", no longer seems to have any effect.
I've set this globally and in my project settings to no avail. I'd really appreciate some advice on how to figure this out.

Thanks!

Incorrect command line options

clangd defines some command line options with type llvm::opt<bool>. The default value can be either true or false. To specify that such an option should be set to false, you would pass --option-name=false on the command line [1].

The relevant code for this issue is in plugin.py on_pre_start:

        for key, value in configuration.init_options.get("clangd").items():
            if not value:
                # False or None
                continue
            elif value is True:
                configuration.command.append(get_argument_for_setting(key))
            elif isinstance(value, str) or isinstance(value, int):
                configuration.command.append("{key}={value}".format(key=get_argument_for_setting(key), value=value))

Any LSP-clangd option that is set to false or zero is skipped. In clangd, --all-scopes-completion defaults to true [2]. I would expect that configuring the LSP-clangd option using "clangd.all-scopes-completion": false would set the option to false, but since the option is skipped, clangd ends up using the default value of true.

This also applies to other options such as malloc-trim, background-index, enable-config, and function-arg-placeholders.

[1] https://llvm.org/docs/CommandLine.html#boolean-arguments
[2] https://github.com/llvm/llvm-project/blob/042dd99484d6f393cc8a365def250e9d74c24d37/clang-tools-extra/clangd/tool/ClangdMain.cpp#L146

__cxx

using namespace std;

std:: can`t appear __cxx11

question about clangd installed by xcode command line tools

Troubleshooting: clangd

Version

  • LSP: 1.27.0
  • Sublime Text: 4169

Server Test Run

  • exit code: 0
  • output
I[16:43:03.915] Apple clangd version 15.0.0 (clang-1500.1.0.2.5)
I[16:43:03.916] Features: mac+xpc
I[16:43:03.916] PID: 4171
I[16:43:03.916] Working directory: /Applications/Sublime Text.app/Contents/MacOS
I[16:43:03.916] argv[0]: /Library/Developer/CommandLineTools/usr/bin/clangd
I[16:43:03.916] argv[1]: --pretty=true
I[16:43:03.916] argv[2]: --clang-tidy=true
I[16:43:03.916] Starting LSP over stdin/stdout

Server Configuration

  • command
[
  "/usr/bin/clangd", 
  "--pretty=true", 
  "--clang-tidy=true"
]
  • shell command
/usr/bin/clangd --pretty=true --clang-tidy=true
  • selector
source.c | source.c++ | source.objc | source.objc++ | source.cuda-c++
  • priority_selector
source.c | source.c++ | source.objc | source.objc++ | source.cuda-c++
  • init_options
{
  "clangd": {
    "all-scopes-completion": null, 
    "background-index": null, 
    "background-index-priority": null, 
    "clang-tidy": true, 
    "compile-commands-dir": null, 
    "completion-style": null, 
    "enable-config": null, 
    "fallback-style": null, 
    "function-arg-placeholders": null, 
    "header-insertion": null, 
    "header-insertion-decorators": null, 
    "limit-references": null, 
    "limit-results": null, 
    "log": null, 
    "malloc-trim": null, 
    "number-workers": null, 
    "path-mappings": null, 
    "pch-storage": null, 
    "pretty": true, 
    "project-root": null, 
    "query-driver": null, 
    "remote-index-address": null
  }, 
  "clangdFileStatus": false, 
  "fallbackFlags": []
}
  • settings
{}
  • env
{}

Active view

  • File name
/Users/zwyyy/Documents/code/leetcode/cpp/2085.count-common-words-with-one-occurrence/solution.cpp
  • Settings
{
  "auto_complete_selector": "meta.tag, source - comment - string.quoted.double.block - string.quoted.single.block - string.unquoted.heredoc", 
  "lsp_active": true, 
  "syntax": "Packages/C++/C++.sublime-syntax"
}
  • base scope
source.c++

Project / Workspace

  • folders
[]
  • is project: False

LSP configuration

{
  "lsp_format_on_save": true, 
  "show_code_actions": "bulb"
}

System PATH

  • /opt/homebrew/bin
  • /opt/homebrew/sbin
  • /usr/local/bin
  • /System/Cryptexes/App/usr/bin
  • /usr/bin
  • /bin
  • /usr/sbin
  • /sbin
  • /var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/local/bin
  • /var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/bin
  • /var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/appleinternal/bin
  • /opt/homebrew/opt/llvm/bin
  • /opt/homebrew/opt/postgresql@15/bin
  • /opt/homebrew/bin
  • /opt/homebrew/Caskroom/miniconda/base/bin
  • /opt/homebrew/Caskroom/miniconda/base/condabin
  • /Users/zwyyy/.orbstack/bin

problem description

There are server clangd in my m1pro mac. One in /usr/bin, which may be installed by xcode command line tools. The other is in /opt/homebrew/opt/llvm/bin,which is installed by brew install llvm. I just install lsp and lsp-clangd package in sb4. It worked well in the past.
The lsp-clangd.sublime-settings is as follow:

  "initializationOptions": {
      "clangd.clang-tidy": true,
      "clangd.pretty": true,
}

One day, I found that when I include <cassert>, it shows that cassert file not found. I don't know why this happed.

The way I solve this problem is change the lsp-clangd.sublime-settings as follows:

{
    "binary": "custom",
    "initializationOptions": {
        "clangd.clang-tidy": true,
        "clangd.pretty": true,
        "custom_command": [
            "/opt/homebrew/opt/llvm/bin/clangd"
        ]
    }
}

Why my previous lsp-clangd settings doesn't work well?

formatting instructions ignored

I'm writing wrt the guide at:

instructions saved in .clang-format were ignored.
Then I tried the settings file. first:

        "clangd.fallback-style": "{IndentWidth: 4}", // as per command line style (I received type warnings when trying to enter in regular object notation)

then:

"command": [
        "/usr/bin/clangd",
        "-i",
        "-style='{IndentWidth: 4}'"
    ]

To no avail.
The following (at the command-line) works fine though:

clangd -i -style='{IndentWidth: 4}' main.c

What am I doing wrong?
What else should I try?

file indentation

For some reason, Sublime's tab width does not generate the effect of indenting a .c file using clangd. When indenting my code (even with tab width with other values) it always indents to the value tab width 2.

How to make clangd works with cuda files

How to make clangd works with cuda files ?
Do I need some specific compilation flags ? I saw on clangd FAQ that we must ensure that the plugin enable clangd when opening cuda files. Is it possible with this plugin ?

how can i get lsp-clangd to check the code based on c++17?

My code is as follows:

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right)
        : val(x), left(left), right(right) {}
};

However, lsp-clangd shows that nullptr is an undeclared identifier. It seems that lsp-clangd checks the code based on c++98, how to change the standard to c++17?

Support running in docker container

So I am wanting to run clangd from a docker container that uses my cross compiler. The paths are all based on the image so it makes it difficult to run from the local machine and doesn't find all the system files. Is it possible to do this already? I remember before when it wasn't a dedicated supported plugin I could overwrite the command but that doesn't seem to be working now.

Two options I see being helpful one that lets me do custom binary option and just set it to whatever. The other is docker binary option but not sure how that looks.

Any suggestions are greatly appreciated. Thank you for your help!

Set compile_commands.json path on a per project basis

Hey @LDAP, thanks so much for looking into it! I can confirm that I can properly configure the system binary to use clangd-12. However I still have another issue that might be relevant to this PR.

My compile_commands.json file is not at the root of the project, so I have to pass --compile-commands-dir arg to clangd-12. Since this path changes for each project, I have to have this setting in the .sublime-project file. I saw you mentioned initializationOptions can now be overwritten per project, so I tried multiple things without success:

  • Use the setting initializationOptions and clangd.compile-commands-dir.
  • Use a custom command with initializationOptions and custom_command. The binary setting was set to custom in the LSP-clangd setting file.

It seems like the plugin doesn't read any settings from the project file for initializationOptions. The JSON auto-completion also doesn't bring any options for any of the keys in initializationOptions (but works when used in the LSP-clangd setting file).

Originally posted by @berteauxjb in #11 (comment)

LSP cannot find opencv headers from msys2 packages

I installed LSP and LSP-clangd as instructions both on my Windows and Linux workstations.
The one on Linux works well but the other one fails to index because it cannot find opencv headers normally.

On Windows, I manage the environment with Msys2 includes Clang 15.0 compiler.
I also installed the packages include the following two:

clang64/mingw-w64-clang-x86_64-opencv 4.6.0-9 [installed]
clang64/mingw-w64-clang-x86_64-eigen3 3.4.0-1 [installed]

The eigen3 library and its headers are indexed correctly, LSP-clangd works well on it.
I wrote the include syntax like

#include <opencv2/opencv.hpp>
The extension raises an error
'opencv2/opencv.hpp' file not found

I generate a copy of compile_commands.json via CMake, but the error remains.
I have no idea to solve the problem, please help me, thanks a lot.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.