Skip to content

Commit 67fa2cd

Browse files
committed
Compose and paste inline Teams images in Org drafts
1 parent 9bb45da commit 67fa2cd

10 files changed

Lines changed: 251 additions & 12 deletions

‎CHANGELOG.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22

33
## Unreleased
44

5+
- Insert an inline image from disk (`C-c i`) or paste it from the clipboard
6+
(`C-c C-p`) in Org chat and channel drafts, including quoted replies.
7+
58
- Overnight scheduled messages now use today's workday start if it is still
69
ahead in the scheduling timezone. Already queued delivery times do not move.
710

‎README.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -306,6 +306,11 @@ in Teams receive formatted text and clickable links, **not raw Org syntax**.
306306
Recipients do not need Emacs or Org. Org composition uses Emacs's built-in
307307
exporter; it does not require Pandoc or an AI service.
308308

309+
In an Org draft, paste a screenshot at point with `C-c C-p`, or choose an
310+
image file with `C-c i`. Move or remove its Org link before sending; recipients
311+
see the image in that position. See [Composition](USAGE.md#composition) for
312+
clipboard helpers, supported formats and scheduled-send limitations.
313+
309314
The major mode is intentionally `org-mode` (or `markdown-mode`):
310315
`teams4e-compose-edit-mode` supplies the Teams commands on top. Its command
311316
keys take precedence over Org/Evil bindings only in the draft, leaving normal

‎USAGE.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,19 @@ Pending state is memory-only; restarting Emacs does not resume this batch.
6767

6868
### Composition
6969

70+
In an **Org** draft, use `C-c i` to insert a PNG, JPEG or GIF from disk,
71+
or `C-c C-p` to paste a screenshot from the clipboard. Both insert an
72+
ordinary Org image link at point. Move or delete the link to move or remove
73+
the image. The draft keeps its own copy until sent or discarded; the
74+
original file is untouched. An existing inline Org file link works too;
75+
Teams4e asks before sending a file from outside the draft's image directory.
76+
77+
Send with `C-c C-c`. Recipients see the image inline, including in replies.
78+
Update both the Emacs package and the Teams4e backend for this feature.
79+
The clipboard command needs `pngpaste` on macOS, `wl-paste` on Wayland,
80+
or `xclip` on X11. Inline images are limited to 4 MiB total per message
81+
and cannot be scheduled. Use `C-c C-a` for an ordinary file attachment.
82+
7083
In a chat compose buffer, type `@` to choose one of the conversation's
7184
participants and insert a real Teams mention. `C-c C-m` invokes the same
7285
command. Use `C-q @` when you need a literal at-sign instead.

‎bin/teams4e_graph.py‎

Lines changed: 40 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3089,6 +3089,36 @@ def quoted_reply_attachment(
30893089
return attachment, marker
30903090

30913091

3092+
def inline_image_payload(message, paths, content_type):
3093+
"""Build Graph hostedContents only from separately supplied image files."""
3094+
if not paths and content_type != "html-inline":
3095+
return {}
3096+
if not paths or content_type != "html-inline":
3097+
raise BackendError("Inline images require an HTML image message")
3098+
hosted = []
3099+
remaining = 4 * 1024 * 1024
3100+
for index, file in enumerate(paths, 1):
3101+
if f'src="../hostedContents/{index}/$value"' not in message:
3102+
raise BackendError("Inline image reference missing from message")
3103+
path = Path(file)
3104+
if not path.is_file():
3105+
raise BackendError("Inline image file is missing")
3106+
with path.open("rb") as image:
3107+
data = image.read(remaining + 1)
3108+
if len(data) > remaining:
3109+
raise BackendError("Inline images exceed 4 MiB; resize or attach as files")
3110+
remaining -= len(data)
3111+
mime = next((mime for prefix, mime in (
3112+
(b"\x89PNG\r\n\x1a\n", "image/png"), (b"\xff\xd8\xff", "image/jpeg"),
3113+
(b"GIF87a", "image/gif"), (b"GIF89a", "image/gif"))
3114+
if data.startswith(prefix)), None)
3115+
if not mime:
3116+
raise BackendError("Unsupported inline image; choose a PNG, JPEG or GIF")
3117+
hosted.append({"@microsoft.graph.temporaryId": str(index), "contentType": mime,
3118+
"contentBytes": base64.b64encode(data).decode("ascii")})
3119+
return {"hostedContents": hosted}
3120+
3121+
30923122
def send_message(
30933123
chat_id: str,
30943124
message: str,
@@ -3100,10 +3130,12 @@ def send_message(
31003130
reply_sender_id: str = "",
31013131
reply_sender_name: str = "",
31023132
reply_preview: str = "",
3133+
inline_images: list[str] | None = None,
31033134
) -> dict[str, Any]:
31043135
"""Send MESSAGE to CHAT_ID, optionally with a native quote attachment."""
31053136
if not message.strip() and not attachment_paths:
31063137
raise BackendError("Message and attachment list are empty")
3138+
images = inline_image_payload(message, inline_images, content_type)
31073139
attachments, attachment_tags = uploaded_reference_attachments(
31083140
attachment_paths or [], access_token
31093141
)
@@ -3115,11 +3147,11 @@ def send_message(
31153147
attachment_tags.insert(0, marker)
31163148
body, mentions = outgoing_body(
31173149
message,
3118-
content_type=content_type,
3150+
content_type="html" if images else content_type,
31193151
mention_specs=mention_specs or [],
31203152
attachment_tags=attachment_tags,
31213153
)
3122-
payload: dict[str, Any] = {"body": body}
3154+
payload: dict[str, Any] = {"body": body, **images}
31233155
if attachments:
31243156
payload["attachments"] = attachments
31253157
if mentions:
@@ -3142,6 +3174,7 @@ def send_channel_message(
31423174
attachment_paths: list[str] | None = None,
31433175
mention_specs: list[str] | None = None,
31443176
content_type: str = "text",
3177+
inline_images: list[str] | None = None,
31453178
) -> dict[str, Any]:
31463179
"""Send a channel root post or a reply."""
31473180
if not message.strip() and not attachment_paths:
@@ -3150,16 +3183,17 @@ def send_channel_message(
31503183
f"/teams/{quoted_id(team_id)}/channels/{quoted_id(channel_id)}/messages"
31513184
)
31523185
path = f"{base}/{quoted_id(reply_to_id)}/replies" if reply_to_id else base
3186+
images = inline_image_payload(message, inline_images, content_type)
31533187
attachments, tags = uploaded_reference_attachments(
31543188
attachment_paths or [], access_token
31553189
)
31563190
body, mentions = outgoing_body(
31573191
message,
3158-
content_type=content_type,
3192+
content_type="html" if images else content_type,
31593193
mention_specs=mention_specs or [],
31603194
attachment_tags=tags,
31613195
)
3162-
payload: dict[str, Any] = {"body": body}
3196+
payload: dict[str, Any] = {"body": body, **images}
31633197
if attachments:
31643198
payload["attachments"] = attachments
31653199
if mentions:
@@ -3990,6 +4024,7 @@ def execute(
39904024
str(option(args, "--replySenderId", required=False) or ""),
39914025
str(option(args, "--replySenderName", required=False) or ""),
39924026
str(option(args, "--replyPreview", required=False) or ""),
4027+
inline_images=options(args, "--inlineImage"),
39934028
)
39944029
with TeamsCache() as cache:
39954030
cache.upsert_messages("chat", str(chat_id), [result])
@@ -4087,6 +4122,7 @@ def execute(
40874122
access_token,
40884123
reply_to_id=option(args, "--replyToId", required=False),
40894124
attachment_paths=options(args, "--attachment"),
4125+
inline_images=options(args, "--inlineImage"),
40904126
mention_specs=options(args, "--mention"),
40914127
content_type=option(args, "--contentType", required=False) or "text",
40924128
)

‎bin/teams4e_mock.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -938,10 +938,15 @@ def _new_message(
938938
body: str,
939939
*,
940940
attachments: list[str] | None = None,
941+
inline_images: list[str] | None = None,
941942
reply_to: str | None = None,
942943
content_type: str = "text",
943944
mention_specs: list[str] | None = None,
944945
) -> dict[str, Any]:
946+
if content_type == "html-inline":
947+
for index, item in enumerate(self._copy_attachments(inline_images or []), 1):
948+
body = body.replace(f'../hostedContents/{index}/$value', item["contentUrl"])
949+
content_type = "html"
945950
message = _message(
946951
f"mock-message-{uuid.uuid4().hex}",
947952
self.state["profile"],
@@ -1011,6 +1016,7 @@ def _send_chat(self, args: list[str]) -> dict[str, Any]:
10111016
message = self._new_message(
10121017
str(option(args, "--message")),
10131018
attachments=options(args, "--attachment"),
1019+
inline_images=options(args, "--inlineImage"),
10141020
reply_to=reply_to,
10151021
content_type=option(args, "--contentType", required=False) or "text",
10161022
mention_specs=options(args, "--mention"),
@@ -1037,6 +1043,7 @@ def _send_channel(self, args: list[str]) -> dict[str, Any]:
10371043
message = self._new_message(
10381044
str(option(args, "--message")),
10391045
attachments=options(args, "--attachment"),
1046+
inline_images=options(args, "--inlineImage"),
10401047
reply_to=reply_to,
10411048
content_type=option(args, "--contentType", required=False) or "text",
10421049
mention_specs=options(args, "--mention"),

‎teams4e-advanced.el‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
(require 'xml)
1919

2020
(declare-function teams4e-transient "advanced")
21+
(declare-function teams4e-compose-paste-inline-image "teams4e-compose" ())
2122
(declare-function teams4e-meeting-availability "teams4e-meetings")
2223
(declare-function teams4e-availability--submission-failed "teams4e-meetings" (buffer payload))
2324
(declare-function agent-shell--resolve-config-designator "agent-shell"
@@ -4170,7 +4171,10 @@ command creates or reuses the chat and opens a blank draft without sending."
41704171
(when (and teams4e-compose--draft-file
41714172
(file-exists-p teams4e-compose--draft-file))
41724173
(delete-file teams4e-compose--draft-file))
4173-
(teams4e-compose--delete-clipboard-attachments))
4174+
(teams4e-compose--delete-clipboard-attachments)
4175+
(when (and teams4e-compose--target (fboundp 'teams4e-compose--image-directory))
4176+
(let ((dir (teams4e-compose--image-directory)))
4177+
(when (file-directory-p dir) (delete-directory dir t)))))
41744178

41754179
(defun teams4e-compose--clipboard-directory ()
41764180
"Return the private directory used for pasted compose images."
@@ -4213,8 +4217,14 @@ command creates or reuses the chat and opens a blank draft without sending."
42134217
(teams4e-compose--schedule-draft)))
42144218

42154219
(defun teams4e-compose-paste-image ()
4216-
"Save the macOS clipboard image and attach it to this Teams draft."
4220+
"Paste an inline image in Org, or attach the macOS clipboard in other editors."
42174221
(interactive)
4222+
(if (derived-mode-p 'org-mode)
4223+
(teams4e-compose-paste-inline-image)
4224+
(teams4e-compose--attach-clipboard-image)))
4225+
4226+
(defun teams4e-compose--attach-clipboard-image ()
4227+
"Save the macOS clipboard image as a file attachment."
42184228
(unless (teams4e-compose-p)
42194229
(user-error "Open a Teams compose buffer first"))
42204230
(let ((program (executable-find "pngpaste")))

‎teams4e-compose.el‎

Lines changed: 83 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,68 @@
1515
(defvar evil-local-mode)
1616
(defvar teams4e-compose-edit-mode)
1717

18+
(defvar teams4e-compose--register-image nil
19+
"During immediate send, function mapping a local image path to a hosted ID.")
20+
21+
(defun teams4e-compose--image-directory ()
22+
"Return the directory for inline images owned by this draft."
23+
(concat (or teams4e-compose--draft-file (teams4e-compose--path)) ".images"))
24+
25+
(defun teams4e-compose--import-image (extension writer)
26+
"Insert an Org image link after WRITER saves image bytes to a new file."
27+
(unless (and (teams4e-compose-p) (derived-mode-p 'org-mode))
28+
(user-error "Open an Org Teams draft to insert an inline image"))
29+
(unless (member extension '("png" "jpg" "jpeg" "gif"))
30+
(user-error "Choose a PNG, JPEG or GIF; use C-c C-a for other files"))
31+
(let ((directory (teams4e-compose--image-directory)) path done)
32+
(make-directory directory t)
33+
(set-file-modes directory #o700)
34+
(setq path (make-temp-file (expand-file-name "image-" directory) nil
35+
(concat "." extension)))
36+
(unwind-protect
37+
(progn
38+
(funcall writer path)
39+
;; Terminal-only Emacs may not have an image decoder.
40+
(unless (with-temp-buffer
41+
(set-buffer-multibyte nil)
42+
(insert-file-contents-literally path nil 0 8)
43+
(goto-char (point-min))
44+
(looking-at-p (regexp-opt '("\211PNG\r\n\032\n" "\377\330\377"
45+
"GIF87a" "GIF89a"))))
46+
(user-error "No PNG, JPEG or GIF image found; draft unchanged"))
47+
(insert (org-link-make-string (concat "file:" path)))
48+
(setq done t)
49+
(when (display-images-p) (org-display-inline-images)))
50+
(unless done (delete-file path)))))
51+
52+
(defun teams4e-compose-insert-image (file)
53+
"Insert a local image at point and keep a private copy with the Org draft."
54+
(interactive "fInsert image: ")
55+
(when (or (file-remote-p file) (not (file-regular-p file)))
56+
(user-error "Choose a local image file"))
57+
(teams4e-compose--import-image
58+
(downcase (or (file-name-extension file) ""))
59+
(lambda (path) (copy-file file path t) (set-file-modes path #o600))))
60+
61+
(defun teams4e-compose-paste-inline-image ()
62+
"Insert the desktop clipboard image at point in this Org draft."
63+
(interactive)
64+
(let* ((args (cond ((eq system-type 'darwin) '("pngpaste" "-"))
65+
((getenv "WAYLAND_DISPLAY") '("wl-paste" "-t" "image/png"))
66+
((getenv "DISPLAY") '("xclip" "-selection" "clipboard" "-t" "image/png" "-o"))
67+
(t (user-error "No desktop clipboard; use C-c i to insert a file"))))
68+
(program (or (executable-find (car args))
69+
(user-error "Clipboard paste requires %s" (car args)))))
70+
(teams4e-compose--import-image
71+
"png" (lambda (path)
72+
(with-temp-buffer
73+
(set-buffer-multibyte nil)
74+
(let ((coding-system-for-read 'no-conversion)
75+
(coding-system-for-write 'no-conversion))
76+
(unless (equal 0 (apply #'call-process program nil (list t nil) nil (cdr args)))
77+
(user-error "Could not read an image from the clipboard"))
78+
(write-region (point-min) (point-max) path nil 'silent)))))))
79+
1880
(defcustom teams4e-compose-editor 'org
1981
"Editor for new Teams drafts.
2082
Org uses the built-in HTML exporter. Markdown requires markdown-mode and
@@ -82,6 +144,10 @@ display if there is insufficient room to split."
82144
(let ((map (copy-keymap teams4e-compose-mode-map))
83145
(commands (make-sparse-keymap)))
84146
(set-keymap-parent map nil)
147+
(when (derived-mode-p 'org-mode)
148+
(define-key map (kbd "C-c i") #'teams4e-compose-insert-image)
149+
(define-key map (kbd "C-c C-p") #'teams4e-compose-paste-inline-image)
150+
(define-key commands [remap org-download-clipboard] #'teams4e-compose-paste-inline-image))
85151
(define-key map (kbd "C-<return>") #'teams4e-compose-send)
86152
(setq-local minor-mode-overriding-map-alist
87153
(cons (cons 'teams4e-compose-edit-mode map)
@@ -351,7 +417,21 @@ The latter cannot recover old reply, attachment, mention or scheduling data."
351417
(when (bound-and-true-p evil-local-mode)
352418
(evil-insert-state))))
353419

354-
(defun teams4e-compose--org-html (source)
420+
(defun teams4e-compose--html-link (link desc info)
421+
"Render inline file images as hosted content; delegate other links to Org."
422+
(if (and (equal "file" (org-element-property :type link))
423+
(org-export-inline-image-p link org-html-inline-image-rules))
424+
(progn
425+
(unless teams4e-compose--register-image
426+
(user-error "Inline images require immediate send; scheduled draft retained"))
427+
(format "<img src=\"../hostedContents/%d/$value\" />"
428+
(funcall teams4e-compose--register-image (org-element-property :path link))))
429+
(org-html-link link desc info)))
430+
431+
(org-export-define-derived-backend 'teams4e-message 'html
432+
:translate-alist '((link . teams4e-compose--html-link)))
433+
434+
(defun teams4e-compose--org-html (source &optional messagep)
355435
"Render SOURCE as a Teams HTML fragment without executing Org code.
356436
External includes, setup files, BIND/CALL directives and macros are not
357437
supported in messages. Refuse them rather than silently reading files
@@ -370,7 +450,7 @@ or evaluating content pasted into a draft."
370450
(org-export-filter-final-output-functions nil)
371451
(org-html-htmlize-output-type nil))
372452
(org-export-string-as
373-
source 'html t
453+
source (if messagep 'teams4e-message 'html) t
374454
'(:with-toc nil :section-numbers nil :with-author nil :with-date nil
375455
:with-title nil :with-sub-superscript nil :with-latex nil
376456
:html-preamble nil :html-postamble nil))))
@@ -405,7 +485,7 @@ or evaluating content pasted into a draft."
405485
(user-error "Switch this draft back to Org, Markdown or Text mode before sending"))
406486
(pcase teams4e-compose--editor
407487
('org (cons "html" (if (string-empty-p source) ""
408-
(teams4e-compose--org-html source))))
488+
(teams4e-compose--org-html source t))))
409489
('markdown (cons "html" (if (string-empty-p source) ""
410490
(teams4e-compose--markdown-html source))))
411491
(_ (cons teams4e-compose--content-type source))))

‎teams4e-ui.el‎

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,8 @@
252252
(declare-function teams4e-compose--start-editor "teams4e-compose" (target reply-to))
253253
(declare-function teams4e-compose--display "teams4e-compose" (buffer origin target))
254254
(declare-function teams4e-compose--render-body "teams4e-compose" (source))
255+
(defvar teams4e-compose--register-image)
256+
(declare-function teams4e-compose--image-directory "teams4e-compose" ())
255257
(declare-function teams4e-outbox-submit "teams4e-outbox" ())
256258
(defvar-local teams4e-compose--editor 'text)
257259
(defvar-local teams4e-compose--schedule nil)
@@ -5410,16 +5412,32 @@ REPLY-TO, when non-nil, is the source message for a native quoted reply."
54105412
(teams4e-compose--effective-mentions message-text)
54115413
teams4e-compose--mentions))
54125414
(label (teams4e--target-label target))
5413-
args)
5415+
inline-images args)
54145416
(when (and (string-empty-p message-text) (null attachments))
54155417
(user-error "Message and attachment list are empty"))
54165418
(when (fboundp 'teams4e-compose--render-body)
5417-
(let ((rendered (teams4e-compose--render-body message-text)))
5419+
(let* ((directory default-directory)
5420+
(owned (teams4e-compose--image-directory))
5421+
(teams4e-compose--register-image
5422+
(lambda (file)
5423+
(let ((path (expand-file-name file directory)))
5424+
(when (or (file-remote-p path) (not (file-regular-p path)))
5425+
(user-error "Inline image is not a local file: %s" file))
5426+
(unless (member path inline-images)
5427+
(unless (or (file-in-directory-p path owned)
5428+
(yes-or-no-p (format "Send local image %s to %s? " path label)))
5429+
(user-error "Image not sent; draft retained"))
5430+
(setq inline-images (append inline-images (list path))))
5431+
(1+ (cl-position path inline-images :test #'equal)))))
5432+
(rendered (teams4e-compose--render-body message-text)))
54185433
(setq content-type (car rendered)
54195434
message-text (cdr rendered))))
54205435
(setq args
54215436
(teams4e--send-args
5422-
target message-text reply-to attachments mentions content-type))
5437+
target message-text reply-to attachments mentions
5438+
(if inline-images "html-inline" content-type)))
5439+
(dolist (path inline-images)
5440+
(setq args (append args (list "--inlineImage" path))))
54235441
(when (or (not teams4e-confirm-send)
54245442
(yes-or-no-p (format "Send this message to %s? " label)))
54255443
(setq header-line-format (format "Sending to %s..." label))

0 commit comments

Comments
 (0)