i have a c++ code file but has pretty ugly indetation. How do i tell emacs to reapply indentation to the file?
Move to the end of the block you want to indent and set the mark by pressing C-SPC . Move the cursor to the first line of the block, and indent this line however far you want all the lines in the block to be indented. Press M-C-\ . The text in the marked block will now be reformatted.
Select the code block, then do C-u - 4 C-x TAB to unindent the marked region by 4 spaces.
This is because standard tabs are set to eight spaces. Tabs are special characters.
C-x h C-M-\
These two commands select the whole buffer and run indent-region
.
Here's the "indent entire buffer" code I place in my ~/.emacs.d/defuns.el
file. I took the extra step and bound it to a quick key, C-x \
. This one also will clear out all your hanging whitspace as well as convert tab characters into their space equivalent representation.
(defun indent-buffer ()
"Indents an entire buffer using the default intenting scheme."
(interactive)
(point-to-register 'o)
(delete-trailing-whitespace)
(indent-region (point-min) (point-max) nil)
(untabify (point-min) (point-max))
(jump-to-register 'o))
(global-set-key "\C-x\\" 'indent-buffer)
Edit, incorporating @JSONs suggestion below will give you a defun that looks like this instead:
(defun indent-buffer ()
"Indents an entire buffer using the default intenting scheme."
(interactive)
(save-excursion
(delete-trailing-whitespace)
(indent-region (point-min) (point-max) nil)
(untabify (point-min) (point-max))))
I tested this out and it works just like before. Thanks for pointing that out JSON.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With