You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Telescope配合nvim-dap选择待调试的C++可执行文件?

解决NvChad中用Telescope替换DAP手动输入可执行文件路径的问题

以下是针对需求的解决方案,直接修改现有nvim-dap的配置即可实现用Telescope模糊查找选择可执行文件:

修改后的完整配置片段

替换你原配置中mfussenegger/nvim-dap的config部分:

{
  "mfussenegger/nvim-dap",
  config = function()
    local dap = require('dap')
    dap.adapters.cppdbg = {
      id = 'cppdbg',
      type = 'executable',
      command = '~/.vscode/extensions/ms-vscode.cpptools-1.25.3-linux-x64/debugAdapters/bin/OpenDebugAD7',
    }

    -- 定义Telescope选择可执行文件的函数
    local function pick_executable()
      local selected_file = nil
      -- 调用Telescope查找文件,限定当前工作目录,过滤非可执行文件
      require('telescope.builtin').find_files({
        cwd = vim.fn.getcwd(),
        prompt_title = "Select Executable",
        -- 过滤规则:排除源文件、目标文件等非可执行类型
        file_ignore_patterns = {
          "%.cpp$", "%.h$", "%.hpp$", "%.o$", "%.obj$", "%.cmake$",
          "CMakeLists.txt", "%.txt$", "%.md$",
        },
        -- 绑定回车事件获取选中文件路径
        attach_mappings = function(_, map)
          map('i', '<CR>', function(prompt_bufnr)
            local entry = require('telescope.actions.state').get_selected_entry()
            require('telescope.actions').close(prompt_bufnr)
            selected_file = entry.path
          end)
          map('n', '<CR>', function(prompt_bufnr)
            local entry = require('telescope.actions.state').get_selected_entry()
            require('telescope.actions').close(prompt_bufnr)
            selected_file = entry.path
          end)
          return true
        end,
      })
      -- 等待用户完成选择后返回路径
      vim.wait(5000, function() return selected_file ~= nil end)
      return selected_file
    end

    dap.configurations.cpp = {
      {
        name = "Launch file",
        type = "cppdbg",
        request = "launch",
        program = pick_executable, -- 替换原手动输入逻辑
        cwd = '${workspaceFolder}',
        stopAtEntry = true,
        setupCommands = {
          {
             text = '-enable-pretty-printing',
             description =  'enable pretty printing',
             ignoreFailures = false
          },
        },
      },
    }
  end
},

关键说明

  1. 自定义选择逻辑:pick_executable函数调用Telescope的find_files弹出选择器,通过file_ignore_patterns过滤掉非可执行文件类型,缩小选择范围。
  2. 选中事件绑定:通过attach_mappings为插入模式和普通模式的回车事件绑定逻辑,获取选中文件路径并关闭选择器。
  3. 等待机制:用vim.wait确保用户完成选择后才返回路径,避免DAP获取到空值导致启动失败。

可选优化

  • 如果需要精准筛选有执行权限的文件,可以替换find_files的查找命令:
    require('telescope.builtin').find_files({
      find_command = { "find", vim.fn.getcwd(), "-type", "f", "-executable", "-printf", "%P\n" },
      -- 其他配置不变
    })
    
  • 可根据项目结构调整file_ignore_patterns,添加或移除需要过滤的文件类型。

内容的提问来源于stack exchange,提问作者PuddingisPOG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 21:17:45