Skip to content

Instantly share code, notes, and snippets.

@schinsue
Forked from dberget/Elixir_Formatter.md
Created February 5, 2018 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schinsue/1ebad94a423feeb19dd8609abf7943e3 to your computer and use it in GitHub Desktop.
Save schinsue/1ebad94a423feeb19dd8609abf7943e3 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

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