That kind of transformation is safer to do on AST (versus regexing code). The formatter provides some inspiration:
def format_string!(string, opts \\ []) when is_binary(string) and is_list(opts) do
line_length = Keyword.get(opts, :line_length, 98)
to_quoted_opts =
[
unescape: false,
warn_on_unnecessary_quotes: false,
literal_encoder: &{:ok, {:__block__, &2, [&1]}},
token_metadata: true
] ++ opts
{forms, comments} = string_to_quoted_with_comments!(string, to_quoted_opts)
to_algebra_opts =
[
comments: comments
] ++ opts
doc = Code.Formatter.to_algebra(forms, to_algebra_opts)
This file has been truncated. show original
In between calls to Code.string_to_quoted_with_comments!
and Code.Formatter.to_algebra
, you could find alias
nodes in the AST and transform them into the desired shape.
OR
You (could use the already-baked version included as a tutorial in the Sourceror docs !
See also the release announcement thread:
Sourceror 0.8.0 is out
This one is a bit small, just bug fixes and the addition of Sourceror.patch_string/2 which allows you to modify just some parts of a string, instead of having to print the whole tree. It receives the original string and a list of patches to be applied.
A patch is just a map with a :range pointing to the start and end positions to be replaced, and a :change that can be either a string, in which case the range will be replaced with it, or a function that acc…
6 Likes