Format APEX code Visual Studio code

You can use uncrustify with VS Code. You need to install the code on your platform (http://uncrustify.sourceforge.net/), and then search for "uncrustify" in VS Code Extensions.

Next, be sure to add this configuration setting. Then the Format Document command and keys will work with Salesforce Apex. I believe you can also accomplish the same thing with the Java language support, but this is working for me.

{    "uncrustify.langOverrides": {
        "apex": "JAVA"
    }
}

I've written up a more detailed howto at https://vernonkeenan.com/index.php/2018/10/13/salesforce-apex-beautified/.


I assume that OP means the part of VS Code that determines standard formatting for Apex files.

If you have Salesforce Extensions installed, typing SHIFT+ALT+F will give an error message:

There is no formatter for 'apex-'-files installed.

Hopefully this will be updated as the SFDX VS project continues but as far as I can see there is no extension that provides this.


Personally, I use the following extensions for vscode:

  1. Salesforce Extensions for VS Code - A package of Salesforce made extensions for editing code. Provides syntax highlighting & will recognize salesforce files based on their extension. Pretty much a must have for working with sfdx.
  2. Apex PMD - provides a tool to analyze code based on a ruleset. Comes with its own ruleset based on java best practices. Useful tool for new developers or old developers working with a codebase which could use a tuneup. It can be modified further to fit your needs.

I asked about supporting an official formatter & was told that it was supported, via a version of prettier. Details can be found here:

https://developer.salesforce.com/tools/vscode/en/user-guide/prettier

Installation

To install the Prettier Apex plugin:

  1. Navigate to the top-level of your project

  2. Check if your project contains the package.json file. If not, run: npm init and accept all the default options.

  3. Run: npm install --save-dev --save-exact prettier prettier-plugin-apex.

You must create a configuration file .prettierrc in the root of your project. If you’d like to know more about formatting options of Prettier, read other config options.

{
  "trailingComma": "none",
  "overrides": [
    {
      "files": "**/lwc/**/*.html",
      "options": { "parser": "lwc" }
    },
    {
      "files": "*.{cmp,page,component}",
      "options": { "parser": "html" }
    }
  ]
}

NOTE: The "trailingComma": "none" setting is required for Aura.

After creating the local configuration file, install the Prettier extension for VS Code.


I'd install the Salesforce extensions for vscode, or some of the individual components. They provide hinting and syntax features which make editing files much easier.


2020: Mavensmate is no longer around. The Salesforce provided extensions work well with SFDX and should meet any other need you have. There is no formatter included in the sfdx package.