Insert screenshots into quarto or rmd files in emacs
Having used org-mode
a lot before quarto came out, one handy thing I could do within it was insert screenshots easily with this answer I found on stackoverflow. I was writing my project notes in quarto
the other day and really missed that functionality. So I tweaked the original elisp
code a bit to make it work for quarto and markdown files (including Rmarkdown).
A demo of how it works:
The function
Edit your emacs init.el
file to include the following function called md-screenshot
. Feel free to name it whatever you want.
(defun md-screenshot ()
"Take a screenshot into a time stamped unique-named file in the
same directory as the working and insert a link to this file."
(interactive)
(setq filename
(concat
(make-temp-name
(concat (file-name-nondirectory (buffer-file-name))
"_screenshots/"
(format-time-string "%Y-%m-%d_%a_%kh%Mm_")) ) ".png"))
(unless (file-exists-p (file-name-directory filename))
(make-directory (file-name-directory filename)))
; take screenshot
(if (eq system-type 'darwin)
(call-process "screencapture" nil nil nil "-i" filename))
(if (eq system-type 'gnu/linux)
(call-process "import" nil nil nil filename))
; insert into file if correctly taken
(if (file-exists-p filename)
(insert (concat "![](" filename ")")))
(markdown-display-inline-images)
(newline))
What it does
It creates a new directory named after the file you want to insert the screenshot in, takes the screenshot, and saves it in the directory with this naming format: Date_Day_Hour_Minute
with a random combination of letters to make unique file names.
In the above demo, the quarto file I was working in was named quarto-screenshot.qmd
Calling the md-screenshot
function did the following:
- created a folder named
quarto-screenshot.qmd_screenshots
within the file’s parent directory - saved the screenshot as
2022-11-15_Tue_13h13m_DA0wve.png
- inserted the following line in the quarto/markdown document:
![](quarto-screenshot.qmd_screenshots/2022-11-15_Tue_13h13m_DA0wve.png)
- ran
markdown-display-inline-images
so the screenshot was displayed within the buffer
Notes
- Use
markdown-toggle-inline-images
to turn off inline display of images in your buffer. - You can make a custom keybinding for it with
(global-set-key "your-key-binding" 'md-screenshot)
. Just replaceyour-key-binding
with whatever you want to use.
References
- stackoverflow answer with the original function for org-mode
- emacs time parsing information so I could format the file name the way I wanted