The call
cell.querySelector('pluto-input .cm-editor').CodeMirror
first selects (with the querySelector) a specific DOM element inside the input of the current cell (specifically the first element with class cm-editor
inside the cell input).
This object happens to be the one that holds the CodeMirror
property that can be used to change the cell code.
For the second point, indeed Pluto does some magic inside and hides output of scripts inside a function that relies on internals and you don’t directly have access to the output when using scripts.
Lastly, the reason why I was suggesting using directly repr
is that it’s just an easier way to get the output of a specific object you want to make permanent (with the caveat that your object needs to have a method defined for MIME"text/html"()
to work easily).
That being said, if what you want to do is really take an image (or any other object with a show
defined for MIME"text/html"
) and make it static/permanent in the notebook, you can do it quite easily using just functions instead of a macro (I had the macro in the solution of this thread as I needed to also know the expression fed to it).
Here is the code of a very small test notebook I just tested (omitting the last cell as it became quite big with the image)
Note that the code used in this notebook does not use anymore the CodeMirror instance directly but relies on some Pluto actions that are accessible from the cells. While this still relies on Pluto internals and is thus not guaranteed to work in the future, I think these internal actions are more stable than relying on extracting the CodeMirror
object directly.
Notebook Code
### A Pluto.jl notebook ###
# v0.20.5
using Markdown
using InteractiveUtils
# ╔═╡ 566835f8-7014-48e7-af47-679c551e5188
using HypertextLiteral
# ╔═╡ a7fbc49f-e32a-43dd-aff4-7cf3d5fcb8d5
using ImageClipboard
# ╔═╡ 2c5464de-db37-45ec-871a-aeb59a867f1f
using Images # Needed to have the show method in HTML
# ╔═╡ 736f6600-06f5-11f0-2cbb-3d4f5a18edee
begin
update_this_cell_content(io::IO) = update_this_cell_content(String(take!(io)))
function update_this_cell_content(content::AbstractString)
@htl("""
<script>
const cell = currentScript.closest("pluto-cell")
const actions = cell._internal_pluto_actions
actions.set_local_cell(cell.id, $(content))
actions.set_and_run_multiple([cell.id])
</script>
""")
end
end
# ╔═╡ bcb4db15-c949-452e-8981-c56d10c8570d
"""
replace_cell_with_show(object)
This function will replace the content of a cell with the output of
```julia
show(io, MIME"text/html"(), object)
```
effectively making the cell content/output static and permanent within a notebook.
!!! note
The actual cell input might become quite long after executing this cell.
"""
function replace_cell_with_show(object)
io = IOBuffer()
println(io, "html", '"', '"', '"')
show(io, MIME"text/html"(), object)
println(io)
print(io, '"', '"', '"')
update_this_cell_content(io)
end
And here is a video example of how this simple function works in action: