Some questions on `startup.jl`

I am configuring the automatic start of OhMyREPL.jl. The document advise putting the following code in the .julia/config/startup.jl file:

atreplinit() do repl
    try
        @eval using OhMyREPL
        println("OhMyREPL imported")    # I add this line
    catch e
        @warn "error while importing OhMyREPL" e
    end
end

Now I have some questions on this code:

  1. Why do I have to write the try...catch...end code segment into the atreplinit() do repl...end?
  2. Why do I have to add an @eval before using OhMyREPL but unnecessarily do that before println(“OhMyREPL imported”)?
  1. Because it can fail, e.g. if the package is not actually installed.
  2. Because all the code between do ... end is an anonymous function, and it is not possible to import modules in a function’s scope. So this is one of those rare cases where it makes sense to use @eval inside a function, so that the instruction is executed in the outer scope.
4 Likes

Thanks for response!

In my first question I actually want to know why is the atreplinit() do repl ... end block necessary?

From the docs

help?> atreplinit
search: atreplinit

  atreplinit(f)

  Register a one-argument function to be called before the REPL interface is initialized in interactive sessions; this is useful to customize the interface. The
  argument of f is the REPL object. This function should be called from within the .julia/config/startup.jl initialization file.

It is added so that OhMyREPL is only loaded when running interactively.
If you are using Julia just to run a script once, like julia compute_something.jl, then you likely don’t need OhMyREPL, so the above prevents that.

3 Likes