Skip to content

Instantly share code, notes, and snippets.

@yibie
Created October 13, 2026 01:23
Show Gist options
  • Select an option

  • Save yibie/9bd280522c24eec41ce0b32b327967cd to your computer and use it in GitHub Desktop.

Select an option

Save yibie/9bd280522c24eec41ce0b32b327967cd to your computer and use it in GitHub Desktop.
org-attach as the single place every file goes: paste, drag, download, readable names, a transient menu
;;; my-org-attach.el --- One place for every file: org-attach with readable names -*- lexical-binding: t -*-
;;; Commentary:
;; Paste, drag-and-drop, org-download and manual attach all end up in
;; `org-attach-attach', so naming and move-vs-copy are decided once, in an
;; :around advice on it:
;;
;; - A file name that says nothing (hash, UUID, IMG_1234, Screenshot…,
;; clipboard-…) becomes "TIMESTAMP-heading-title.ext". Readable names
;; are kept.
;; - Files are moved, not copied: nothing is left behind where they came from.
;;
;; Needs Emacs 30+ / Org 9.7+ (`org-yank-dnd-method') and transient.
;; The clipboard, Quick Look and Finder commands are macOS only; pasting
;; images needs pngpaste (brew install pngpaste).
;;
;; Setup:
;;
;; (require 'my-org-attach)
;; (my/org-attach-setup)
;;
;; which binds C-c C-a to the menu and s-v to the smart paste in Org buffers.
;;; Code:
(require 'org)
(require 'org-attach)
(require 'transient)
(defvar org-download-method)
(defvar org-download-file-format-function)
(defvar my/org-attach-download-dir "~/Downloads/"
"Where `my/org-attach-latest-download' looks for the newest file.")
(defvar my/org-attach-generated-name-regexps
'("\\`[0-9a-f]\\{16,\\}\\'"
"\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f-]+\\'"
"\\`[0-9_. -]+\\'"
"\\`wechatimg[0-9]+\\'"
"\\`[0-9]+_\\.pic\\(_hd\\)?\\'"
"\\`\\(img\\|dsc\\|pxl\\)[_-]?[0-9]+"
"\\`clipboard-"
"\\`\\(screenshot\\|screen shot\\|截屏\\|截图\\|屏幕截图\\|屏幕快照\\)"
"\\`\\(image\\|img\\|download\\|unnamed\\|untitled\\|file\\)\\([ _-]?[0-9]*\\)\\'")
"Base names (no extension, case-insensitive) that say nothing about the content.")
(defvar my/org-attach-slug-length 24
"Maximum width of the heading part of a generated file name.")
;;; Naming
(defun my/org-attach--slug ()
"The current heading (or the file title) squeezed into a file-name fragment."
(let* ((title (or (and (derived-mode-p 'org-mode)
(not (org-before-first-heading-p))
(org-get-heading t t t t))
(and (derived-mode-p 'org-mode)
(cadar (org-collect-keywords '("TITLE"))))
""))
(text (if (string-match org-link-bracket-re title)
(replace-regexp-in-string
org-link-bracket-re
(lambda (m) (or (match-string 2 m) "")) title)
title))
(slug (string-trim (replace-regexp-in-string "[^[:alnum:]]+" "-" text)
"-+" "-+")))
(string-trim-right
(truncate-string-to-width slug my/org-attach-slug-length) "-+")))
(defun my/org-attach--generated-name-p (base)
"Non-nil when BASE (no extension) looks machine-generated."
(let ((case-fold-search t))
(seq-some (lambda (re) (string-match-p re base))
my/org-attach-generated-name-regexps)))
(defun my/org-attach-timestamp-name (ext)
"Return \"TIMESTAMP-heading.EXT\". EXT has no dot and may be nil."
(let ((slug (my/org-attach--slug)))
(concat (format-time-string "%Y%m%d-%H%M%S")
(unless (string-empty-p slug) (concat "-" slug))
(when (and ext (not (string-empty-p ext))) (concat "." ext)))))
(defun my/org-attach-readable-name (file)
"The name FILE should get: kept if readable, otherwise a timestamp name."
(let ((name (file-name-nondirectory file)))
(if (my/org-attach--generated-name-p (file-name-sans-extension name))
(my/org-attach-timestamp-name (file-name-extension name))
name)))
(defun my/org-attach--unique-name (name dir)
"Return NAME, or NAME with -2, -3… before the extension if DIR has it already."
(let ((base (file-name-sans-extension name))
(ext (file-name-extension name t))
(n 1)
(candidate name))
(while (file-exists-p (expand-file-name candidate dir))
(setq n (1+ n)
candidate (format "%s-%d%s" base n ext)))
candidate))
(defun my/org-attach--attach-a (orig file &optional visit-dir method)
"Around advice for `org-attach-attach': uniform names, cp becomes mv.
Only regular local files attached with cp or mv are touched; ln, lns,
url, none and directories are passed to ORIG unchanged."
(let ((effective (or method org-attach-method)))
(if (or (not (memq effective '(cp mv)))
(not (file-regular-p file)))
(funcall orig file visit-dir method)
(let* ((file (expand-file-name file))
(name (my/org-attach--unique-name
(my/org-attach-readable-name file)
(org-attach-dir 'get-create))))
(if (string= name (file-name-nondirectory file))
(funcall orig file visit-dir 'mv)
;; Rename in a staging directory. The original is deleted only
;; after the attach succeeded, so a failure halfway loses nothing.
(let* ((stage (make-temp-file "org-attach" t))
(staged (expand-file-name name stage)))
(unwind-protect
(progn
(copy-file file staged nil t)
(prog1 (funcall orig staged visit-dir 'mv)
(delete-file file)))
(delete-directory stage t))))))))
(defun my/org-download-file-name (filename)
"For `org-download-file-format-function': same naming for downloads."
(my/org-attach-readable-name filename))
;;; Links
(defun my/org-attach--insert-link (name)
"Insert a link to attachment NAME. Images get no description, so they inline."
(let ((beg (point))
(image (string-match-p (image-file-name-regexp) name)))
(insert (org-link-make-string (concat "attachment:" name)
(unless image name)))
(when (and image (fboundp 'org-link-preview-region))
(ignore-errors (org-link-preview-region t t beg (point))))))
(defun my/org-attach--files ()
"Attachment file names of the current heading; error if there are none."
(let ((dir (org-attach-dir)))
(or (and dir (org-attach-file-list dir))
(user-error "No attachments on this heading"))))
(defun my/org-attach--read (prompt)
"Pick one attachment of the current heading with PROMPT.
With a single attachment, return it without asking."
(let ((files (my/org-attach--files)))
(if (cdr files)
(completing-read prompt files nil t)
(car files))))
;;; Clipboard
(defun my/org-attach--clipboard-text ()
"Text on the clipboard, or the empty string."
(let ((text (ignore-errors (gui-get-selection 'CLIPBOARD))))
(if (stringp text) (substring-no-properties text) "")))
(defun my/org-attach--clipboard-has-image-p ()
"Non-nil when the clipboard carries image data."
(seq-some (lambda (target) (string-prefix-p "image/" (symbol-name target)))
(ignore-errors (gui-get-selection 'CLIPBOARD 'TARGETS))))
(defun my/org-attach--clipboard-wants-image-p ()
"Non-nil when this paste should be treated as an image.
Image only: yes. Image plus text: look at the text. \"Copy image\" in a
browser adds one line with the URL, copying an image file in Finder adds
its name; both count as images. Anything else (cells copied from a
spreadsheet come with a rendered picture) is text."
(let ((text (string-trim (my/org-attach--clipboard-text))))
(cond
((string-empty-p text) t)
((string-match-p "\n" text) nil)
(t (or (string-match-p "\\`\\(https?\\|file\\|data\\):" text)
(string-match-p (image-file-name-regexp) text))))))
(defun my/org-attach--clipboard-image-to (file)
"Write the clipboard image to FILE. Return nil if there is none."
(and (executable-find "pngpaste")
(zerop (call-process "pngpaste" nil nil nil file))))
(defun my/org-attach--paste-image ()
"Attach the clipboard image and insert a link. Return nil if there is none."
;; The clipboard- prefix is on the generated-name list, so the advice
;; renames the file; there is no naming logic here.
(let ((tmp (expand-file-name
(format-time-string "clipboard-%Y%m%dT%H%M%S.png")
temporary-file-directory)))
(when (my/org-attach--clipboard-image-to tmp)
(let ((link (car (org-attach-attach tmp nil 'mv))))
(my/org-attach--insert-link (string-remove-prefix "attachment:" link))
t))))
;;; Commands
;;;###autoload
(defun my/org-attach-paste ()
"Attach the clipboard image to the current heading, or yank as usual."
(interactive)
(unless (and (my/org-attach--clipboard-has-image-p)
(my/org-attach--clipboard-wants-image-p)
(my/org-attach--paste-image))
(call-interactively #'org-yank)))
;;;###autoload
(defun my/org-attach-paste-image ()
"Attach the clipboard image no matter what text comes with it."
(interactive)
(or (my/org-attach--paste-image)
(user-error "No image on the clipboard")))
(defun my/org-attach--latest-download ()
"Newest regular file in the download directory, skipping partial downloads."
(car (sort (seq-filter
(lambda (f)
(and (file-regular-p f)
(not (string-match-p
"\\.\\(crdownload\\|download\\|part\\|tmp\\)\\'" f))))
(directory-files my/org-attach-download-dir t "\\`[^.]"))
#'file-newer-than-file-p)))
;;;###autoload
(defun my/org-attach-latest-download ()
"Attach the newest file in the download directory and insert a link."
(interactive)
(let ((file (or (my/org-attach--latest-download)
(user-error "The download directory is empty"))))
(when (y-or-n-p (format "Attach %s? " (file-name-nondirectory file)))
(let ((link (car (org-attach-attach file))))
(my/org-attach--insert-link (string-remove-prefix "attachment:" link))))))
;;;###autoload
(defun my/org-attach-file (file)
"Attach FILE to the current heading and insert a link."
(interactive "fAttach file: ")
(let ((link (car (org-attach-attach file))))
(my/org-attach--insert-link (string-remove-prefix "attachment:" link))))
;;;###autoload
(defun my/org-attach-insert-link ()
"Insert a link to one of the current heading's attachments."
(interactive)
(my/org-attach--insert-link (my/org-attach--read "Insert link to: ")))
;;;###autoload
(defun my/org-attach-rename ()
"Rename an attachment and rewrite the links to it in this subtree."
(interactive)
(let* ((dir (org-attach-dir))
(old (my/org-attach--read "Rename attachment: "))
(ext (file-name-extension old t))
(base (read-string (format "New name (%s is kept): " ext)
(file-name-sans-extension old)))
(new (concat (file-name-sans-extension
(if (string-suffix-p ext base) base (concat base ext)))
ext)))
(when (string-empty-p (file-name-sans-extension new))
(user-error "The name cannot be empty"))
(unless (string= old new)
(rename-file (expand-file-name old dir) (expand-file-name new dir))
(let ((count 0)
(re (concat "\\(attachment:\\)"
(regexp-opt (list old (org-link-escape old)))
"\\(\\]\\|::\\)")))
(save-excursion
(save-restriction
(unless (org-before-first-heading-p)
(org-narrow-to-subtree))
(goto-char (point-min))
(while (re-search-forward re nil t)
(replace-match (concat "\\1" (org-link-escape new) "\\2") t)
(setq count (1+ count)))))
(message "Renamed to %s, rewrote %d link(s)" new count)))))
;;;###autoload
(defun my/org-attach-quick-look ()
"Preview an attachment with macOS Quick Look."
(interactive)
(let ((file (expand-file-name (my/org-attach--read "Preview: ")
(org-attach-dir))))
(start-process "org-attach-quick-look" nil "qlmanage" "-p" file)))
;;;###autoload
(defun my/org-attach-reveal-in-finder ()
"Show the attachment directory in Finder, selecting a lone attachment."
(interactive)
(let* ((dir (or (org-attach-dir) (user-error "No attachments on this heading")))
(files (org-attach-file-list dir)))
(if (and files (not (cdr files)))
(call-process "open" nil nil nil "-R" (expand-file-name (car files) dir))
(call-process "open" nil nil nil dir))))
;;;###autoload (autoload 'my/org-attach-menu "my-org-attach" nil t)
(transient-define-prefix my/org-attach-menu ()
"Attachments of the current heading."
[["Add"
("a" "Pick a file" my/org-attach-file)
("l" "Newest download" my/org-attach-latest-download)
("v" "Clipboard image" my/org-attach-paste-image)
("u" "From URL" org-attach-url)
("b" "Contents of a buffer" org-attach-buffer)]
["View"
("o" "Open" org-attach-open)
("p" "Quick Look" my/org-attach-quick-look)
("f" "Reveal in Finder" my/org-attach-reveal-in-finder)
("F" "Directory in Dired" org-attach-reveal-in-emacs)
("i" "Insert link to existing" my/org-attach-insert-link)]
["Organise"
("r" "Rename" my/org-attach-rename)
("d" "Delete one" org-attach-delete-one)
("z" "Sync directory and tag" org-attach-sync)
("s" "Set attachment directory" org-attach-set-directory)
("?" "Stock dispatcher" org-attach)]])
;;; Setup
;;;###autoload
(defun my/org-attach-setup ()
"Send every way a file enters an Org buffer through org-attach."
(setq org-yank-dnd-method 'attach ; drag a file in: attach, don't ask
org-yank-image-save-method 'attach ; yanked images go to the attach dir
;; Only matters if you use org-download.
org-download-method 'attach
org-download-file-format-function #'my/org-download-file-name)
(advice-add 'org-attach-attach :around #'my/org-attach--attach-a)
(keymap-set org-mode-map "C-c C-a" #'my/org-attach-menu)
(keymap-set org-mode-map "s-v" #'my/org-attach-paste))
(provide 'my-org-attach)
;;; my-org-attach.el ends here
@artelse

artelse commented Oct 26, 2026

Copy link
Copy Markdown

Have been an org-download user for quite some time and also am wanting to change a few things you are describing here. I like it when an image is just a file link and not an attachment and copies from the file manager clipboard (URI) just work.
I've added an interactive annotation function to ask for a caption and have that inserted. However, it would be cool to have the caption and file name the same. I do some elisp coding, but am still learning.
Thanks for all the work you do for emacs :)

@yibie

yibie commented Oct 27, 2026

Copy link
Copy Markdown
Author

@artelse :-) happy to know that. I'm use org-attatch, because I don't want to manage files in other side, I want to keep it clean in one time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment