How to use macros to install and load a package?

I was thinking of writing something like

macro use(ex)
    quote
        Pkg.add(string($ex))
        using $ex
    end
end

but I fear that’s not how to use it.

How do I write a macro taking in a nonexisting module name so that it can generate code that installs it?

@use Symbolics

Bonus task: check if package is already installed.

The main use case would be to use it inside Pluto, but I could image it to be quite useful in general.

Julia v1.7 will have this feature built-in:
https://github.com/JuliaLang/julia/pull/39026

4 Likes

As I see this it would only work in the REPL, but does not provide a general option to implement this in other front ends like Pluto.

Pluto has it’s own version of the feature in the works, by the way: https://github.com/fonsp/Pluto.jl/pull/844

2 Likes

What I am struggling with is how do I generate a string from a Symbol passed to a macro.
Would this be the correct way of implementing it?

macro use(pkg)
    str = String(pkg)
    quote
        Pkg.add($str)
        using $pkg
    end
end

Not sure what’s going on with that. Maybe you are forgetting an esc. I always write macros as esc from a helper function to avoid those issues.

julia> macro use(pkg)
           esc(use_helper(pkg))
       end;

julia> function use_helper(pkg)
           p = string(pkg)
           quote 
               import Pkg; 
               Pkg.add($p)
               using $pkg
           end
       end;