# How to programatically format code using plugins

**URL:** <https://forum.elixirforum.com/t/how-to-programatically-format-code-using-plugins/58533>\
**Category:** Questions\
**Tags:** formatter, code\
**Created:** [September 28, 2023, 4:05am UTC](https://forum.elixirforum.com/t/how-to-programatically-format-code-using-plugins/58533 "2023-09-28T04:05:09Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![fceruti](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/fceruti/32/28850_2.png) [@fceruti](https://forum.elixirforum.com/u/fceruti)\
**Post date:** [September 28, 2023, 4:05am UTC](https://forum.elixirforum.com/t/how-to-programatically-format-code-using-plugins/58533/1 "2023-09-28T04:05:09Z")

</div>

I’m building a library that’s constantly re generating certain modules, building them from string templates. The generated modules include certain sigils that are nicely formatted using a [custom plugin](https://hexdocs.pm/elixir/main/Code.html#format_string!/2).

I need to format the string before it touches disk, because there are also file watchers, who would receive the event twice if I format as a second separate step. That’s why I can’t just call `System.cmd("mix format")` after creating the file.

Is there something equivalent to using [Code.format\_string!/2](https://hexdocs.pm/elixir/main/Code.html#format_string!/2) but with the ability of passing a plugin list?

Thanks!

---

<div class="post-metadata">

**Author:** ![krasenyp](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/krasenyp/32/39733_2.png) [@krasenyp](https://forum.elixirforum.com/u/krasenyp)\
**Post date:** [September 28, 2023, 6:21am UTC](https://forum.elixirforum.com/t/how-to-programatically-format-code-using-plugins/58533/2 "2023-09-28T06:21:37Z")

</div>

`mix format -` reads from standard input and prints to standard output. I haven’t tested it but I suspect you can use it in conjunction with heredoc and skip the writing to stdin. If you want to batch the formatting you can first write to temporary files and format them with one call to `mix format`.

---

<div class="post-metadata">

**Author:** ![fceruti](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/fceruti/32/28850_2.png) [@fceruti](https://forum.elixirforum.com/u/fceruti)\
**Post date:** [September 28, 2023, 7:37pm UTC](https://forum.elixirforum.com/t/how-to-programatically-format-code-using-plugins/58533/3 "2023-09-28T19:37:19Z")

</div>

After a very unsucessful attempt to communicate with `mix format -` using [Port](https://hexdocs.pm/elixir/1.15.6/Port.html), I ended up doing this:

```elixir
  def write_and_format_module(file_path, content) do
    filename = for _ <- 1..5, into: "", do: <<Enum.random('0123456789abcdef')>>
    tmp_file = "/tmp/tmp_#{filename}.ex"
    :ok = File.write(tmp_file, content)
    System.cmd("mix", ["format", tmp_file])
    File.rename(tmp_file, file_path)
    Logger.info("Re generated: #{file_path}")
  end

```

---

<div class="post-metadata">

**Author:** ![krasenyp](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/krasenyp/32/39733_2.png) [@krasenyp](https://forum.elixirforum.com/u/krasenyp)\
**Post date:** [September 29, 2023, 12:16pm UTC](https://forum.elixirforum.com/t/how-to-programatically-format-code-using-plugins/58533/4 "2023-09-29T12:16:00Z")

</div>

You can go even simpler:

```elixir
def write_and_format_module(file_path, content) do
    command = """
    mix format - <<STDIN > #{file_path}
    #{content}
    STDIN
    """
    {"", 0} = System.shell(command)
    Logger.info("Re generated: #{file_path}")
  end

```

---

<div class="post-metadata">

**Author:** ![fceruti](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/fceruti/32/28850_2.png) [@fceruti](https://forum.elixirforum.com/u/fceruti)\
**Post date:** [September 29, 2023, 5:20pm UTC](https://forum.elixirforum.com/t/how-to-programatically-format-code-using-plugins/58533/5 "2023-09-29T17:20:52Z")

</div>

awesome, thanks!

---

<div class="post-metadata">

**Author:** ![Marcus](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/marcus/32/24640_2.png) [@Marcus](https://forum.elixirforum.com/u/Marcus)\
**Post date:** [September 30, 2023, 7:47am UTC](https://forum.elixirforum.com/t/how-to-programatically-format-code-using-plugins/58533/6 "2023-09-30T07:47:48Z")

</div>

If I understand right you want to format in `dev` mode and therefore you can access `Mix`. In this case you can use this:

```elixir
> iex -S mix
iex(1)> {formatter, _opts} = Mix.Tasks.Format.formatter_for_file("source.ex")
{#Function<19.89531025/1 in Mix.Tasks.Format.find_formatter_for_file/2>,
 [
   sigils: [],
   plugins: [FreedomFormatter],
   trailing_comma: true,
   inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"],
   locals_without_parens: [noop: 1]
 ]}
iex(2)> formatter.("""
...(2)> defmodule Foo do
...(2)> def foo do
...(2)> noop 5
...(2)> [
...(2)> 1,
...(2)> 2,
...(2)> ]
...(2)> end
...(2)> end
...(2)> """) |> IO.puts()
defmodule Foo do
  def foo do
    noop 5

    [
      1,
      2,
    ]
  end
end

:ok

```

The `"source.ex"` given to `formatter_for_file` does not have to be an existing file.

---

<div class="post-metadata">

**Author:** ![fceruti](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/fceruti/32/28850_2.png) [@fceruti](https://forum.elixirforum.com/u/fceruti)\
**Post date:** [October 12, 2023, 6:26pm UTC](https://forum.elixirforum.com/t/how-to-programatically-format-code-using-plugins/58533/7 "2023-10-12T18:26:57Z")

</div>

> [@Marcus](#):
>
> `Mix.Tasks.Format.formatter_for_file("source.ex")`

Thanks! this was it 🙂

```elixir
  def write_and_format_module(file_path, content) do
    :ok = file_path |> Path.dirname() |> File.mkdir_p()
    {formatter, _} = Mix.Tasks.Format.formatter_for_file("source.ex")
    File.write(file_path, formatter.(content))
    IO.puts(IO.ANSI.green() <> "* creating " <> IO.ANSI.reset() <> file_path)
  end

```
