This tutorial explains how to format automatically as well as a shortcut for it.
How to Auto format code line of code or a file or a project in Netbeans
We can do it in multiple ways One way is to use UI Menu items
- Go to the
Source
menu - Select
Format
Another way, using Netbeans shortcuts for code indention
In Windows/Linux:
Alt
+Shift
+F
In Mac
Ctrl
+Shift
+F
For a Single file, Select the line of code or the whole file and run the above shortcut
For a group of files or project level, Run the same shortcut, It shows a popup asking Recursively format selected files and folders?.
Click on
OK
to format the code in all files in a projectClick on
cancel
to cancel the format operation
You can still change this shortcut to new binding keys.
How to assign a shortcut for code format in Netbeans
- Go to the
Tools
Menu - Select
Options
Menu Item - It opens the Options window
- Select the
Keymap
tab - type “Format” in the search box
- Select Actions that contain
Format
- Change shortcut from Alt + Shift + F to new key binding
- Click on the
OK
button
Netbeans macro for auto format indentation
- Go to the
Tools
Menu - Select
Options
Menu Item - It opens the Options window
- Select the
Editor
tab - Select
Macros
in sub-tabbed panes - Create a new macro by clicking the
New
button - Please give Macro Name as autoformat-macro
- Enter the following lines in the macro code box
indent-line caret-line-first-column caret-begin-line
- Assign the shortcut to the new binding Shift + A
- Whenever Shift + A is the key pressed in the file, It automatically formats the code as per the indentation configured in the macro.