Salesforce Apex Beautified in VS Code with Uncrustify
Why Beautify?
As a Salesforce Apex coder I admit to being a little persnickety when it comes to my code. Who doesn’t want their code to look just the way you want it to? But, when working in teams personal coding habits can lead to conflict.
What to do? Your dev team can’t have internal battles over spaces or tabs!
Fortunately, long before Silicon Valley parodied the anal-retentive nature of coders, a technical solution has been figured out. It’s called a code beautifier and it’s built right into today’s hottest IDE: Microsoft VS Code.
The idea behind using a code beautifier and using a coding standard for your code appearance is to standardize your formatting for the benefit of your fellow coders. We all know how one gets used to how curly braces are used in as class or method definition. If your coding buddy doesn’t have the same philosophy, it creates angst and conflict when you have to re-wire your brain to read this mess!
JavaScript and TypeScript coders have the benefit of prettier, a Microsoft-supplied VS Code extension that will auto-format your JavaScript code.
To beautify Salesforce Apex in VS Code one needs to recite some magical incantations with a new extension called Uncrustify.
While no one has made an Apex-specific beautifier yet, we can use the VS Code extension uncrustify and it’s ability to format Java, a close cousin of Apex. The trick is to tell uncrustify to treat Apex files like Java.
Steps To Auto-Format Apex in VS Code with Uncrustify
- Visit and star the vscode-uncrustify Github repository to show your appreciation!
- Linux users download and install the repo. Mac users install with
brew install uncrustify
or see http://macappstore.org/uncrustify. Windows users download the binary from Sourceforge and install it in your PATH. - Install the Uncrustify VS Code Extension and reload.
- Set up a default configuration file in your current workspace with
uncrustify.create
command. - Tell uncrustify to treat Apex like Java with this setting:
{ "uncrustify.langOverrides": {
"apex": "JAVA"
}
}
That is it! Now the VS Code format
command should format your document. Select part of your file, right click and you’ll have a Format Selection
command available. Be sure to check the read.me and learn about all options.
Now your code will be beautiful and your team can resume their fight about your tech stack!