/format Command

The /format command allows you to format and beautify code in various programming languages. It helps improve code readability by standardizing indentation, spacing, and syntax formatting.

Available Subcommands

/format code

Formats code in a specific programming language.

Usage

/format code language: <language> code: <code to format>

Options

OptionDescriptionRequiredPlatform
languageProgramming language of the codeYesDiscord (parameter), Slack (flag with —language)
codeCode to formatYesDiscord (parameter), Slack (flag with —code)

Supported Languages

The /format command supports the following programming languages:

  • JSON: Indents and structures JSON data
  • JavaScript: Formats JavaScript code
  • TypeScript: Formats TypeScript code
  • JSX: Formats JSX (React) code
  • HTML: Formats HTML markup
  • XML: Formats XML markup
  • CSS: Formats CSS stylesheets
  • SCSS: Formats SCSS (Sass) stylesheets
  • SQL: Formats SQL queries with keyword capitalization
  • Go: Formats Go code
  • PHP: Formats PHP code

Platform-Specific Implementation

Discord Implementation

  • Uses Discord’s named parameter system (e.g., language:, code:)
  • Responses appear as embedded messages with syntax highlighting
  • The formatted code is displayed in a code block with proper language syntax highlighting
  • Discord users select the language from a dropdown of supported options

Slack Implementation

  • Supports two input formats:
    1. Flag-based approach with quotes: /format --language <language> --code "<code>" (legacy approach)
    2. Flag-based approach with backticks (recommended): /format --language javascript --code function() `
  • The backtick approach is the recommended and preferred method for all Slack commands
  • No need to escape special characters when using backticks, making it much cleaner
  • Particularly useful for JSON and other complex code where escaping would be problematic
  • Responses are shown with formatted blocks displaying the result
  • The formatted code is presented in a code block with language-specific syntax highlighting
  • Includes a list of supported languages in the help message when no parameters are provided

Examples by Language

JSON

Before:

{"name":"John","age":30,"city":"New York","skills":["JavaScript","PHP","Go"],"contact":{"email":"john@example.com","phone":"123-456-7890"}}

Command:

/format code language: JSON code: {"name":"John","age":30,"city":"New York","skills":["JavaScript","PHP","Go"],"contact":{"email":"john@example.com","phone":"123-456-7890"}}

After:

{
  "name": "John",
  "age": 30,
  "city": "New York",
  "skills": [
    "JavaScript",
    "PHP",
    "Go"
  ],
  "contact": {
    "email": "john@example.com",
    "phone": "123-456-7890"
  }
}

JavaScript

Before:

function calculateTotal(items){const total=items.reduce((acc,item)=>{return acc+item.price*item.quantity},0);return total.toFixed(2);}

Command:

/format code language: JavaScript code: function calculateTotal(items){const total=items.reduce((acc,item)=>{return acc+item.price*item.quantity},0);return total.toFixed(2);}

After:

function calculateTotal(items) {
  const total = items.reduce((acc, item) => {
    return acc + item.price * item.quantity
  }, 0);
  return total.toFixed(2);
}

TypeScript

Before:

interface Product{id:number;name:string;price:number;}class ShoppingCart{private items:Product[]=[];constructor(){}addItem(product:Product,quantity:number=1):void{this.items.push(product);}}

Command:

/format code language: TypeScript code: interface Product{id:number;name:string;price:number;}class ShoppingCart{private items:Product[]=[];constructor(){}addItem(product:Product,quantity:number=1):void{this.items.push(product);}}

After:

interface Product {
  id: number;
  name: string;
  price: number;
}

class ShoppingCart {
  private items: Product[] = [];
  
  constructor() {}
  
  addItem(product: Product, quantity: number = 1): void {
    this.items.push(product);
  }
}

JSX

Before:

function App(){const [count,setCount]=React.useState(0);return(<div className="app"><h1>Counter App</h1><div className="counter">{count}</div><div className="buttons"><button onClick={()=>setCount(count-1)}>Decrease</button><button onClick={()=>setCount(count+1)}>Increase</button></div></div>);}

Command:

/format code language: JSX code: function App(){const [count,setCount]=React.useState(0);return(<div className="app"><h1>Counter App</h1><div className="counter">{count}</div><div className="buttons"><button onClick={()=>setCount(count-1)}>Decrease</button><button onClick={()=>setCount(count+1)}>Increase</button></div></div>);}

After:

function App() {
  const [count, setCount] = React.useState(0);
  return (
    <div className="app">
      <h1>Counter App</h1>
      <div className="counter">{count}</div>
      <div className="buttons">
        <button onClick={() => setCount(count - 1)}>Decrease</button>
        <button onClick={() => setCount(count + 1)}>Increase</button>
      </div>
    </div>
  );
}

HTML

Before:

<!DOCTYPE html><html><head><title>My Page</title></head><body><header><h1>Welcome</h1><nav><ul><li><a href="/">Home</a></li><li><a href="/about">About</a></li></ul></nav></header><main><p>Content goes here.</p></main></body></html>

Command:

/format code language: HTML code: <!DOCTYPE html><html><head><title>My Page</title></head><body><header><h1>Welcome</h1><nav><ul><li><a href="/">Home</a></li><li><a href="/about">About</a></li></ul></nav></header><main><p>Content goes here.</p></main></body></html>

After:

<!DOCTYPE html>
<html>
  <head>
    <title>My Page</title>
  </head>
  <body>
    <header>
      <h1>Welcome</h1>
      <nav>
        <ul>
          <li><a href="/">Home</a></li>
          <li><a href="/about">About</a></li>
        </ul>
      </nav>
    </header>
    <main>
      <p>Content goes here.</p>
    </main>
  </body>
</html>

XML

Before:

<users><user id="1"><n>John Doe</n><email>john@example.com</email><roles><role>admin</role><role>editor</role></roles></user><user id="2"><n>Jane Smith</n><email>jane@example.com</email><roles><role>user</role></roles></user></users>

Command:

/format code language: XML code: <users><user id="1"><n>John Doe</n><email>john@example.com</email><roles><role>admin</role><role>editor</role></roles></user><user id="2"><n>Jane Smith</n><email>jane@example.com</email><roles><role>user</role></roles></user></users>

After:

<users>
  <user id="1">
    <n>John Doe</n>
    <email>john@example.com</email>
    <roles>
      <role>admin</role>
      <role>editor</role>
    </roles>
  </user>
  <user id="2">
    <n>Jane Smith</n>
    <email>jane@example.com</email>
    <roles>
      <role>user</role>
    </roles>
  </user>
</users>

CSS

Before:

body{font-family:Arial,sans-serif;margin:0;padding:0;}.container{width:1200px;margin:0 auto;}header{background-color:#333;color:white;padding:1rem;}nav ul{list-style:none;display:flex;}nav li{margin-right:1rem;}

Command:

/format code language: CSS code: body{font-family:Arial,sans-serif;margin:0;padding:0;}.container{width:1200px;margin:0 auto;}header{background-color:#333;color:white;padding:1rem;}nav ul{list-style:none;display:flex;}nav li{margin-right:1rem;}

After:

body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
}

.container {
  width: 1200px;
  margin: 0 auto;
}

header {
  background-color: #333;
  color: white;
  padding: 1rem;
}

nav ul {
  list-style: none;
  display: flex;
}

nav li {
  margin-right: 1rem;
}

SQL

Before:

select u.id, u.name, u.email, count(o.id) as order_count from users u left join orders o on u.id = o.user_id where u.created_at > '2023-01-01' group by u.id, u.name, u.email having count(o.id) > 5 order by order_count desc limit 10;

Command:

/format code language: SQL code: select u.id, u.name, u.email, count(o.id) as order_count from users u left join orders o on u.id = o.user_id where u.created_at > '2023-01-01' group by u.id, u.name, u.email having count(o.id) > 5 order by order_count desc limit 10;

After:

SELECT u.id, u.name, u.email, COUNT(o.id) as order_count
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE u.created_at > '2023-01-01'
GROUP BY u.id, u.name, u.email
HAVING COUNT(o.id) > 5
ORDER BY order_count DESC
LIMIT 10;

Go

Before:

package main;import("fmt";"time");func main(){now:=time.Now();fmt.Println("Current time:",now);for i:=0;i<5;i++{fmt.Println("Count:",i)};if x:=10;x>5{fmt.Println("x is greater than 5")}}

Command:

/format code language: Go code: package main;import("fmt";"time");func main(){now:=time.Now();fmt.Println("Current time:",now);for i:=0;i<5;i++{fmt.Println("Count:",i)};if x:=10;x>5{fmt.Println("x is greater than 5")}}

After:

package main

import (
  "fmt"
  "time"
)

func main() {
  now := time.Now()
  fmt.Println("Current time:", now)
  
  for i := 0; i < 5; i++ {
    fmt.Println("Count:", i)
  }
  
  if x := 10; x > 5 {
    fmt.Println("x is greater than 5")
  }
}

PHP

Before:

<?php

function calculate_statistics($numbers) {
    if (empty($numbers)) {return null;}$total = array_sum($numbers);
    $count = count($numbers);$average = $total / $count;$sorted_numbers = $numbers;
    sort($sorted_numbers);
    $median = ($count % 2 !== 0) ? 
    $sorted_numbers[floor($count / 2)] : ($sorted_numbers[floor($count / 2) - 1] + $sorted_numbers[floor($count / 2)]) / 2;
    return ["count" => $count,"total" => $total,"average" => $average,"median" => $median
    ];
}

Command:

/format code language: PHP code: <?php

function calculate_statistics($numbers) {
    if (empty($numbers)) {return null;}$total = array_sum($numbers);
    $count = count($numbers);$average = $total / $count;$sorted_numbers = $numbers;
    sort($sorted_numbers);
    $median = ($count % 2 !== 0) ? 
    $sorted_numbers[floor($count / 2)] : ($sorted_numbers[floor($count / 2) - 1] + $sorted_numbers[floor($count / 2)]) / 2;
    return ["count" => $count,"total" => $total,"average" => $average,"median" => $median
    ];
}

After:

<?php

function calculate_statistics($numbers) {
    if (empty($numbers)) {
        return null;
    }
    $total = array_sum($numbers);
    $count = count($numbers);
    $average = $total / $count;
    $sorted_numbers = $numbers;
    sort($sorted_numbers);
    $median = ($count % 2 !== 0) ? $sorted_numbers[floor($count / 2)] : ($sorted_numbers[floor($count / 2) - 1] + $sorted_numbers[floor($count / 2)]) / 2;
    return [
        "count" => $count,
        "total" => $total,
        "average" => $average,
        "median" => $median
    ];
}

SCSS

Before:

/* SCSS Variables */
$spacing: 20px;
$main-font: Arial, sans-serif;

/* Nested styles */
body {
  font-family:$main-font;
  margin:0;
  padding:0;
}

.container {
  width:1200px;margin:0 auto;padding:$spacing;
  
  header{padding:$spacing; h1{margin-bottom:20px;}}
}

Command:

/format code language: SCSS code: /* SCSS Variables */
$spacing: 20px;
$main-font: Arial, sans-serif;

/* Nested styles */
body {
  font-family:$main-font;
  margin:0;
  padding:0;
}

.container {
  width:1200px;margin:0 auto;padding:$spacing;
  
  header{padding:$spacing; h1{margin-bottom:20px;}}
}

After:

/* SCSS Variables */
$spacing: 20px;
$main-font: Arial, sans-serif;

/* Nested styles */
body {
  font-family: $main-font;
  margin: 0;
  padding: 0;
}

.container {
  width: 1200px;
  margin: 0 auto;
  padding: $spacing;

  header {
    padding: $spacing;
    h1 {
      margin-bottom: 20px;
    }
  }
}

How It Works

The formatter applies language-specific formatting rules:

  1. JSON: Properly indents and structures JSON with standardized spacing
  2. JavaScript/TypeScript: Formats braces, indentation, and spacing
  3. JSX: Formats React JSX code with proper component and attribute spacing
  4. HTML/XML: Properly indents tags and attributes
  5. CSS/SCSS: Formats selectors, properties, and values with consistent spacing
  6. SQL: Capitalizes SQL keywords and formats spacing
  7. Go: Applies basic Go formatting standards
  8. PHP: Formats according to PHP style guidelines

Implementation Details

The code formatting is powered by Prettier, a popular code formatter known for its consistency and flexibility. For language-specific formatting:

  • JavaScript/TypeScript/JSX: Uses Prettier with the Babel parser
  • HTML/XML: Uses Prettier’s HTML parser
  • CSS/SCSS: Uses Prettier with PostCSS and SCSS syntax support

When using the /format command, the code is processed by the appropriate Prettier plugin based on the language specified, ensuring optimal formatting according to each language’s conventions.

Limitations

  • Maximum code size is limited due to Discord and Slack message constraints
  • For very complex or large code, only a portion may be returned
  • Language-specific formatters may have varying capabilities
  • Syntax errors in the input code may result in formatting failures

Use Cases

  • Improve code readability before sharing with others
  • Clean up minified or poorly formatted code
  • Standardize code formatting in discussions
  • Make code examples more presentable in team conversations
  • Learn proper code formatting standards for different languages

Notes

  • The formatted code will be displayed in a syntax-highlighted code block
  • Formatting very large code snippets may be truncated due to message limitations
  • For Slack, we strongly recommend using backticks for all code:
    • Recommended approach: Use backticks for clean syntax without escaping: /format --language javascript --code function() `
    • Alternative approach: Use double quotes with escaped special characters: /format --language javascript --code "function() {}"