/
indents.jl
61 lines (51 loc) · 1.6 KB
/
indents.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
"""
indent(fun, io, n[; indent_first=true, kwargs...])
Print all the output of `fun` to `io` indented by `n` spaces. If
`!indent_first`, the first line is _not_ indented. `kwargs...` are
passed on to `printstyled`.
# Examples
```jldoctest
julia> indent(stdout, 6) do io
println(io, "Hello")
println(io, "World")
end
Hello
World
```
"""
function indent(fun::Function, io::IO, n::Int; indent_first=true, kwargs...)
indentation = repeat(" ", n)
for (i,l) in enumerate(split(rstrip(redirect_output(fun)), "\n"))
(indent_first || i > 1) && write(io, indentation)
printstyled(io, l; kwargs...)
println(io)
end
end
"""
indent(fun, io, first_line::String[; kwargs...])
Variant of [`indent`](@ref) that will first print `first_line` and
then print all the output from `fun` indented by the length of
`first_line`. `kwargs` are passed on to `printstyled`.
# Examples
```jldoctest
julia> indent(stdout, "Important information: ") do io
println(io, "Hello")
println(io, "World")
end
Important information: Hello
World
julia> indent(stdout, "Important information: ") do io
print_boxed(io) do io
println(io, "Hello")
println(io, "World")
end
end
Important information: ┌ Hello
└ World
```
"""
function indent(fun::Function, io::IO, first_line::String; kwargs...)
printstyled(io, first_line; kwargs...)
n = textwidth(last(split(first_line, "\n")))
indent(fun, io, n; indent_first=false, kwargs...)
end