reddit / emacs

Help with indentation for C++

EMWaveHunter · 2022-02-22 18:45
Hello, I'm trying to understand how to get Emacs working to indent C++ code the way I want it to. Namely, I want to get rid of hanging braces in my code. I know you can select a region and auto indent it by pressing C-M-\\, however that doesn't seem to remove hanging braces even though my style is set to not have hanging braces. For example, if I highlight the following function and run auto indent test_function(void) { std::cout << "This is a test" << std::endl; } I would like it to become test_function(void){ std::cout << "This is a test" << std::endl; } but it doesn't. Anyone know how to make emacs do this? Thanks,
I0delay · 2022-02-22 19:12
Have a look at the clang-format package.
EMWaveHunter · 2022-02-22 19:50
I installed clang-format with package-install, but when I run indent it just displays (clang-format: success) and doesn't actually change any code formatting. Hmm, not sure what I'm doing wrong.
SlowValue · 2022-02-22 23:25
Just to be sure, you are not asking about settings in `c-hanging-braces-alist`, right? > Controls the insertion of newlines before and after braces when the auto-newline feature is active.
I0delay · 2022-02-23 02:40
This is how i have set up clang-format ``` (require 'clang-format) (setq clang-format-executable "/path/to/clang-format") (setq clang-format-style "file") (defun clang-format-save-hook-for-this-buffer () "Create a buffer local save hook." (add-hook 'before-save-hook (lambda () (when (locate-dominating-file "." ".clang-format") (clang-format-buffer)) nil) nil t)) (defun add-clang-format-hook () (add-hook 'before-save-hook 'clang-format-this-buffer nil t)) (add-hook 'c++-mode-hook (lambda () (clang-format-save-hook-for-this-buffer))) ``` With this setup, you'll also have to add a file .clang-format to your project directory. The documentation for that file is [here](https://clang.llvm.org/docs/ClangFormatStyleOptions.html). Now, whenever you save, your current c++-file will be formatted.
EMWaveHunter · 2022-02-23 04:41
Yeah, I believe I changed that setting but it doesn't seem to format already written code correctly (code with hanging braces) when I run auto indent on the region.
EMWaveHunter · 2022-02-28 20:49
Thanks so much! This is working amazingly. I also added: (global-set-key (kbd "C-c i") 'clang-format-region) (global-set-key (kbd "C-c u") 'clang-format-buffer) to my init file: Interestingly, the indent region C-M-\\ doesn't indent the same way as C-c i clang-format-region