@peccul is peccu

(love peccu '(emacs lisp cat outdoor bicycle mac linux coffee))

Emacsのorg-modeに画像を貼り付けたかのように振る舞う

tl;dr

画面キャプチャを所定のフォルダ1から所定のフォルダ2へコピーしてコピー後のパスをorg-modeのリンクにすれば画像を張り付けたように見える。という発想で関数を ChatGPTに書いてもらった。

  ;; generated by ChatGPT
  ;; https://chatgpt.com/share/0ca4b7b0-ecc6-41c3-9454-9588aefba8e4

  (defun my/copy-latest-file-and-insert-org-link (source-dir target-dir)
    "Copy the latest file from SOURCE-DIR to a subdirectory of TARGET-DIR based on the current date,
and insert the org-mode image link at point."
    (interactive "DSource directory: \nDTarget directory: ")
    (let* ((files (directory-files source-dir t "^[^.].*"))
           (latest-file (car (sort files (lambda (a b) (time-less-p (nth 5 (file-attributes b))
                                                                    (nth 5 (file-attributes a)))))))
           (file-name (file-name-nondirectory latest-file))
           (current-year (format-time-string "%Y"))
           (current-month (format-time-string "%m"))
           (target-subdir (expand-file-name (concat current-year "/" current-month) target-dir))
           (target-path (expand-file-name file-name target-subdir)))
      (unless (file-directory-p target-subdir)
        (make-directory target-subdir t))
      (copy-file latest-file target-path t)
      (insert (format "[[file:%s]]" target-path))))

  (defun my/insert-image-like-logsec ()
    (interactive)
    (my/copy-latest-file-and-insert-org-link "path/to/ScreenCapture" "path/to/assets"))

  (global-set-key (kbd "M-V") 'my/insert-image-like-logsec)

  ;; you can show image inline in org-mode
  ;; (add-hook 'org-mode-hook 'org-display-inline-images)
  ;; M-x org-toggle-inline-images (C-c C-x C-v)
  ;; M-x org-display-inline-images
  ;; M-x org-remove-inline-images

背景とか

org-mode風のLogseqを使っていて便利だけどやっぱりEmacsに統一したかった。

統一できない理由が画面キャプチャをさっと埋め込む機能を捨てられないところだったのでそこを何とか解決した話。

しばらくクリップボードから取り込むところに執着してしまい yank-media 周辺を調べていたけれど、Windows向けの公開されているEmacsだとなんかうまく使えなくてとん挫していた。

ある時急に、そもそも画面キャプチャに使っている GreenShot が毎回所定のフォルダにキャプチャを保存してるんだから、 それを org-mode から見える場所か .org ファイルに近い場所 にコピーしてそこへのパスを書けばいいのではと気づいた。

気づいたあとはChatGPTに関数を書いてもらって、キーバインド設定してうまくいった。あーうれしい。

細かいところに言及すると、コピー先フォルダに大量の画像ファイルが蓄積してdiredとか遅くなるので年月のフォルダも作るようにしている。

org-modeで画像をインライン表示するのは、 org-mode-hook で常に表示するか、手動でトグルするか。

役割 関数 キーバインド
表示する org-display-inline-images
非表示にする org-remove-inline-images
表示をトグルする org-toggle-inline-images C-c C-x C-v
(デフォルトかどうか調べていない)

hookに入れるなら

(add-hook 'org-mode-hook 'org-display-inline-images)

参考

  • ChatGPTのログ

https://chatgpt.com/share/0ca4b7b0-ecc6-41c3-9454-9588aefba8e4

  • 私の設定の該当箇所

github.com

  • せっかくなので yank-media 関連もリンクだけ貼っておく。いつか使える環境になった時のために

github.com

www.gnu.org

github.com

superuser.com

Paste an image on clipboard to Emacs Org mode file without saving it : r/emacs

stackoverflow.com

github.com

www.gnu.org

emacs.stackexchange.com