Skip to content

Instantly share code, notes, and snippets.

@dberget
Last active February 20, 2018 03:42
Show Gist options
  • Save dberget/f4d157603a90cda95f289c06858dd04c to your computer and use it in GitHub Desktop.
Save dberget/f4d157603a90cda95f289c06858dd04c to your computer and use it in GitHub Desktop.
Some notes on using Elixir's code formatter

Example of .formatter.exs file

[
  inputs: ["mix.exs", "{config,lib,test}/**/*.{ex,exs}"],
  locals_without_parens: [
    # Kernel
    inspect: 1,
    inspect: 2,

    # Phoenix
    plug: 1,
    plug: 2,
    action_fallback: 1,
    render: 2,
    render: 3,
    render: 4,
    redirect: 2,
    socket: :*,
    get: :*,
    post: :*,
    resources: :*,
    pipe_through: :*,
    delete: :*,
    forward: :*,
    channel: :*,
    transport: :*,

    # Ecto Schema
    field: 2,
    field: 3,
    belongs_to: 2,
    belongs_to: 3,
    has_one: 2,
    has_one: 3,
    has_many: 2,
    has_many: 3,
    embeds_one: 2,
    embeds_one: 3,
    embeds_many: 2,
    embeds_many: 3,
    many_to_many: 2,
    many_to_many: 3,
    add: 3,

    # Ecto Query
    from: 2
  ]
]

Git

Pre-Commit Script

#!/bin/sh
#.git/hooks/pre-commit

exfiles=$(git diff --cached --name-only --diff-filter=ACM "*.ex" "*.exs" | tr '\n' ' ')
[ -z "$exfiles" ] && exit 0
echo "$exfiles" | xargs mix format

echo "$exfiles" | xargs git add
exit 0

VSCode

Create Task (tasks.json)

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "elixir-formatter",
            "type": "shell",
            "command": "mix format",
            "args": [
                "${file}"
            ],
            "presentation": {
                "reveal": "never"
            },
            "problemMatcher": [
                "$mixCompileError"
            ]
        }
    ]
}

Format on Save

{
  "key": "cmd+s",          
  "when": "editorFocus && editorLangId == 'elixir'",
  "command": "workbench.action.tasks.runTask", 
  "args": "elixir-formatter"
}

VSCode Vim Keybinding (User Settings)

 "vim.otherModesKeyBindingsNonRecursive": [
        {
            "before": [
                "leader",
                "f"
            ],
            "after": [],
            "commands": [
                {
                    "command": "workbench.action.tasks.runTask",
                    "args": "elixir-formatter"
                }
            ]
        },

Sublime

With the SublimeOnSaveBuild extension, you can put this in your project settings:

{
	"settings": {
		"build_on_save": 1,
		"filename_filter": "\\.(exs?)$"
	},
	"build_systems":
	[
		{
			"name": "mix format",
			"shell_cmd": "mix format --check-equivalent $file"
		}
	]
}

Then select Tools -> Build System -> mix format to automatically format on save

@dberget
Copy link
Author

dberget commented Jan 18, 2018

Fixed, thanks @DianaOlympos! 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment