Bash autocompletion of CMake targets

I have requests from one of my consulting clients to add support for auto-completing target names when typing commands like cmake --build . --target <TAB>. I’ve often wanted something similar myself. I’ve been thinking about this for a while, and I’m wondering if we can use the most recent replies of the CMake file API to provide the details for this to work. Not sure yet quite how to hook it all up, given that the only things you can rely on being installed are CMake and bash, so no JSON-processing tools, but maybe CMake’s own JSON processing would be good enough. In theory, the bash completion could run CMake scripts to provide the results, so I think there’s potentially a viable path, although performance may be something to keep a close eye on.

Before I go spending on any time on this, I wanted to ask if anyone has any thoughts or objections to such an approach? It would have to rely on something having made a file API query in an earlier CMake run to work, but that seems like a reasonable minimum requirement for such functionality to work.

1 Like

Perhaps a cmake -E bash-completion-helper tool could be added to do the heavy lifting.

CMake Issue 19168 discusses an idea to let users opt-in to having all their CMake build trees get file-api replies automatically. That could be useful in conjunction with this.

1 Like

I would love to have this for --preset as well.

Auto-completion for preset names should already work. I use it often in my daily work. You might need to source certain files to get it enabled though (I had to add some things to the ~/.bashrc due to some quirks with how bash completions work or how they load things, never really figured out precisely why they didn’t work out-of-the-box).

Huh, and so it does. It wasn’t working in a particular terminal I was trying it on at the time, but that was within an IDE, must be something with the way the bash environment was being loaded there

Auto-completion also works for Ninja generator.

ninja -C build <tab>
Display all 311 possibilities? (y or n)