Crystal Code Formatter: What Does It Do?

Adler @ 2015-10-17

Crystal code formatter comes with 0.9.0 release. It is a tool for automatically checking and correcting the style of code in a project. Like Ruby, Crystal does not force styling in format, but following a specific way of formatting code will make your project more accessible to others.

Run Formatter

Currently the you can run the following command in a Crystal project to initiate the formatter.

crystal tool format

It checks for all .cr file and changing the format. All files will be altered and saved, so remember to commit everything (or make them revertible) before you run this command.

What It Does

The following formats will be corrected with the formatter. Not all examples are included here.

Indentaion is always two spaces

All nested indentation is two spaces.

def foo

Tabs, and any number of spaces other than two will be altered.

Spaces between operators, commas, and comments

a+b                        # => a + b
hash[a+b]                  # => hash[a + b]
array.inject(0){|r,v|r+=1} # => array.inject(0) { |r, v| r += 1 }
#todo                      # => # todo

Extra spaces will be removed if there are more than one space.

No parentheses for methods with no arguments

foo()     # => foo
def foo() # => def foo

Many developers from C, Java, or JavaScript tend to write functions with parentheses; however, Crystal prefers no parentheses in such cases.

Arguments in method definitions should be surrounded with parantheses

def foo val : Bool
# should be 
def foo(val : Bool)

I believe this one is very important with type restrictions, since type restrictions without parentheses can either be the type of arguments or of returned types. It will not be misunderstood by the programs, but might be a little confusing to readers.

Removing extra spaces between code and comments

The following

foo       # => "bar"

will turn into:

foo # => "bar"

However, it won't remove the spaces if it's for alignment like:

foo    # => "bar"
foobar # => "foobar"

Furthermore, it aligns the code and comments for you. Sweet, isn't it :)

Extra line between class property and methods

The following

class Foo
  property bar
  def foobar

will turn into:

class Foo
  property bar

  def foobar

Extra space in documenting code

If we document method foo we might do this:

foo #=> "bar"

But Crystal prefers a space between the sharp sign and the equal sign:

foo # => "bar"


There's an alternative for Sublime Text users to use this feature with Crystal package, instead of running commands in terminal. I believe plugins in other editors will include this feature soon.

I'm really glad that Crystal has released a tool as a reference for all Crystal developers. It helps projects more accessible for others, which also helps Crystal to be production-ready quickly.