Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

with_terminal to capture stdout and stdin #31

Merged
merged 12 commits into from
Sep 20, 2020
5 changes: 4 additions & 1 deletion Project.toml
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
name = "PlutoUI"
uuid = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
authors = ["Fons van der Plas <fonsvdplas@gmail.com>"]
version = "0.6.2"
version = "0.6.3"

[deps]
Base64 = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f"
Logging = "56ddb016-857b-54e1-b83d-db4d58db5568"
Dates = "ade2ca70-3891-5945-98fb-dc099432e06a"
Markdown = "d6f4376e-aef5-505a-96c1-9c027394607a"
Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"
Suppressor = "fd094767-a336-5f1f-9728-57cf17d0bbfb"

[compat]
julia = "^1"
Suppressor = "^0.2.0"
1 change: 1 addition & 0 deletions src/PlutoUI.jl
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@ const PKG_ROOT_DIR = normpath(joinpath(@__DIR__, ".."))
include("./Builtins.jl")
include("./Clock.jl")
include("./Resource.jl")
include("./Terminal.jl")

end
65 changes: 65 additions & 0 deletions src/Terminal.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
export with_terminal

import Suppressor: @color_output, @capture_out, @capture_err
import Logging: ConsoleLogger, with_logger
import Markdown: htmlesc

const terminal_css = """
<style>
div.PlutoUI_terminal {
border: 5px solid pink;
border-radius: 12px;
font-size: .65rem;
background-color: #333;
}
div.PlutoUI_terminal pre {
color: #ddd;
background-color: transparent;
margin-block-end: 0;
}
div.PlutoUI_terminal pre.err {
color: #ff5f5f;
}
</style>
"""

"""
Run the function, and capture all messages to `stdout`. The result will be a small terminal displaying the captured text.

This allows you to to see the messages from `println`, `dump`, `Pkg.status`, etc.

Example:

```julia
with_terminal() do
x=1+1
println(x)
@warn "Oopsie!"
end
```

```julia
with_terminal(dump, [1,2,[3,4]])
```

"""
function with_terminal(f::Function, args...; kwargs...)
local spam_out, spam_err
@color_output false begin
spam_out = @capture_out begin
spam_err = @capture_err begin
with_logger(ConsoleLogger(stdout)) do
f(args...; kwargs...)
end
end
end
end

HTML("""
$(terminal_css)
<div class="PlutoUI_terminal">
<pre>$(htmlesc(spam_out))</pre>
$(isempty(spam_err) ? "" : "<pre class='err'>" * htmlesc(spam_err) * "</pre>")
</div>
""")
end