reddit / emacs

Can lsp-mode generate and reload compile_commands with cmake automatically?

OldMansKid · 2022-09-28 14:07
I use VSCode on desktop and it does so automatically when CMakeList.txt is updated. I also need to edit code in terminal so I use Emacs. Does lsp-mode support this? I currently have to manually run cmake and move compile\_commands.json to the project root, then reload the project whenever CMakeList.txt is modified. I feel like that I'm doing things the wrong way.
yyoncho · 2022-09-28 17:36
There is no such feature. You may open feature request in lsp-mode repo
[deleted] · 2022-09-29 03:34
[removed]
Lucius_Martius · 2022-09-29 03:52
You can add a custom target like the following to your CMakeLists.txt to move the updated file automatically: add_custom_target( CopyCompileCommands ALL ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_BINARY_DIR}/compile_commands.json ${CMAKE_CURRENT_LIST_DIR} ) I'm not sure about lsp-mode, but eglot with clangd seems to pick up changes to the file automatically.
OldMansKid · 2022-09-30 06:05
I went off to learn a little Lisp, and managed to write a function to run cmake automatically when CMakeLists.txt is changed: (defun GetParent (path) (file-name-directory (directory-file-name path))) (require 'filenotify) (defvar rootCMakeLists nil) (defvar projectRoot nil) (defvar buildDir nil) (defvar genCmd nil) (defun RunCMake (event) (shell-command genCmd) (shell-command (concat "cp " buildDir "compile_commands.json " projectRoot)) (message "executed cmake")) (defun CheckProject () (let ((cmakeFile "CMakeLists.txt") (currentPath default-directory) (lastPath default-directory) (curFilePath nil)) (when (file-exists-p cmakeFile) (setq curFilePath (concat currentPath cmakeFile)) (while (file-exists-p curFilePath) (setq lastPath currentPath) (setq currentPath (GetParent currentPath)) (setq curFilePath (concat currentPath cmakeFile)) ) (setq projectRoot lastPath) (dolist (item (directory-files-recursively projectRoot cmakeFile)) (file-notify-add-watch item '(change) 'RunCMake)) (setq buildDir (concat projectRoot "Build")) (unless (file-directory-p buildDir) (make-directory buildDir)) (setq genCmd (concat "cmake -B " buildDir " -S " projectRoot)) ) ) ) (add-hook 'lsp-mode-hook 'CheckProject)