Commit bf9234c365

bf9234c365eef78d8a545504009ffb85bab727f8

parent: 42e3e3e8fa

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-12 05:01 UTC

Paste, drop and take photos into notes on iOS

An image pasted in the editor is saved as org-yank-image-save-method says and
linked at the caret; dropped files are attached and linked. Attach Photo or
Video and the new Take Photo insert their links at the caret. The manual
covers pasting and dropping, and the two new settings.

Layout: unified · split

Sources/OrgstarMobile/CameraPicker.swift added +35
@@ -0,0 +1,35 @@
1#if os(iOS)
2import SwiftUI
3import UIKit
4
5/// The camera, for a photo to attach; `taken` gets its JPEG data, or nil when cancelled.
6struct CameraPicker: UIViewControllerRepresentable {
7 let taken: (Data?) -> Void
8
9 static var isAvailable: Bool { UIImagePickerController.isSourceTypeAvailable(.camera) }
10
11 func makeUIViewController(context: Context) -> UIImagePickerController {
12 let picker = UIImagePickerController()
13 picker.sourceType = .camera
14 picker.delegate = context.coordinator
15 return picker
16 }
17
18 func updateUIViewController(_ picker: UIImagePickerController, context: Context) {}
19
20 func makeCoordinator() -> Coordinator { Coordinator(taken: taken) }
21
22 final class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
23 let taken: (Data?) -> Void
24 init(taken: @escaping (Data?) -> Void) { self.taken = taken }
25
26 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
27 taken((info[.originalImage] as? UIImage)?.jpegData(compressionQuality: 0.9))
28 }
29
30 func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
31 taken(nil)
32 }
33 }
34}
35#endif
Sources/OrgstarMobile/EditorScreen.swift +16 −2
@@ -63,6 +63,7 @@ struct EditorScreen: View {
6363 /// org-attach's file picker is up, for this method.
6464 @State private var attaching: Attachments.Method?
6565 @State private var attachingPhotos = false
66 @State private var takingPhoto = false
6667 @State private var photos: [PhotosPickerItem] = []
6768 /// A file shown in Quick Look.
6869 @State private var previewed: URL?
@@ -149,6 +150,9 @@ struct EditorScreen: View {
149150 Menu("Attachments", systemImage: "paperclip") {
150151 Button("Attach File…", systemImage: "doc.badge.plus") { attaching = .cp }
151152 Button("Attach Photo or Video…", systemImage: "photo.badge.plus") { attachingPhotos = true }
153 if CameraPicker.isAvailable {
154 Button("Take Photo…", systemImage: "camera") { takingPhoto = true }
155 }
152156 Button("Attach File from URL…", systemImage: "link.badge.plus") { attachActions.run("app.attach.url") }
153157 Button("New Attachment…", systemImage: "square.and.pencil") { attachActions.run("app.attach.new") }
154158 Button("Open Attachment…", systemImage: "paperclip") { attachActions.run("app.attach.open") }
@@ -275,6 +279,13 @@ struct EditorScreen: View {
275279 }
276280 }
277281 .photosPicker(isPresented: $attachingPhotos, selection: $photos, matching: .any(of: [.images, .videos]))
282 .fullScreenCover(isPresented: $takingPhoto) {
283 CameraPicker { data in
284 takingPhoto = false
285 if let data { attachActions.yankImage(data, ext: "jpg", prefix: "photo") }
286 }
287 .ignoresSafeArea()
288 }
278289 .onChange(of: photos) { _, items in
279290 guard !items.isEmpty else { return }
280291 photos = []
@@ -415,6 +426,9 @@ struct EditorScreen: View {
415426 editor.onAgenda = { start, count in model.agendaRequest = .init(start: start, count: count) }
416427 editor.keymap = model.keymap
417428 editor.modal = model.modalKeys
429 // Dropped files are copies the drop made, so they are attached, not linked or opened.
430 editor.onFiles = { attachActions.drop($0, method: .attach, attachMethod: .mv) }
431 editor.onImage = { attachActions.yankImage($0, ext: $1) }
418432 editor.onAppCommand = { id in
419433 if Self.paneCommands.contains(id) {
420434 if let onPaneCommand { onPaneCommand(id) } else { message = "Not available here" }
@@ -507,7 +521,7 @@ extension EditorScreen {
507521 pick: { attaching = $0 })
508522 }
509523
510 /// Photos and videos attached under the names Photos gives them.
524 /// Photos and videos attached under the names Photos gives them, linked at the caret.
511525 private func attachPhotos(_ items: [PhotosPickerItem]) {
512526 Task { @MainActor in
513527 var urls: [URL] = []
@@ -515,7 +529,7 @@ extension EditorScreen {
515529 if let picked = try? await item.loadTransferable(type: PickedFile.self) { urls.append(picked.url) }
516530 }
517531 if urls.count < items.count { message = "Can't read \(items.count - urls.count) of the items" }
518 if !urls.isEmpty { attachActions.attach(urls, method: .mv) }
532 if !urls.isEmpty { attachActions.drop(urls, method: .attach, attachMethod: .mv) }
519533 }
520534 }
521535
Sources/OrgstarMobile/KeyedTextView+Media.swift added +75
@@ -0,0 +1,75 @@
1#if os(iOS)
2import UIKit
3import UniformTypeIdentifiers
4
5/// Images pasted and files dropped on the text view, for `yank-media` and Org's drag-and-drop
6/// handlers. Text goes to the text system as before.
7extension KeyedTextView: UITextDropDelegate {
8 /// The image on `pasteboard` and the extension for it, when there is no text: PNG, JPEG
9 /// and GIF as they are, anything else UIKit reads as PNG.
10 static func image(on pasteboard: UIPasteboard) -> (data: Data, ext: String)? {
11 guard !pasteboard.hasStrings, pasteboard.hasImages else { return nil }
12 for (type, ext) in [(UTType.png, "png"), (.jpeg, "jpeg"), (.gif, "gif")] {
13 if let data = pasteboard.data(forPasteboardType: type.identifier) { return (data, ext) }
14 }
15 return pasteboard.image?.pngData().map { ($0, "png") }
16 }
17
18 override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
19 if action == #selector(paste(_:)), isEditable, onImage != nil, MobileEditor.pasteboard.hasImages { return true }
20 return super.canPerformAction(action, withSender: sender)
21 }
22
23 override func paste(_ sender: Any?) {
24 if isEditable, let image = Self.image(on: MobileEditor.pasteboard), onImage?(image.data, image.ext) == true { return }
25 super.paste(sender)
26 }
27
28 /// A drop of files without text, which the editor attaches.
29 func takesDrop(_ session: any UIDropSession) -> Bool {
30 isEditable && onFiles != nil && !session.hasItemsConforming(toTypeIdentifiers: [UTType.plainText.identifier])
31 && session.items.allSatisfy { $0.itemProvider.registeredContentTypes.contains { $0.conforms(to: .data) } }
32 }
33
34 func textDroppableView(_ textDroppableView: UIView & UITextDroppable, proposalForDrop drop: any UITextDropRequest) -> UITextDropProposal {
35 guard takesDrop(drop.dropSession) else { return drop.suggestedProposal }
36 let proposal = UITextDropProposal(operation: .copy)
37 proposal.dropPerformer = .delegate
38 return proposal
39 }
40
41 func textDroppableView(_ textDroppableView: UIView & UITextDroppable, willPerformDrop drop: any UITextDropRequest) {
42 guard takesDrop(drop.dropSession) else { return }
43 selectedRange = NSRange(location: offset(from: beginningOfDocument, to: drop.dropPosition), length: 0)
44 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("Dropped-\(UUID().uuidString)")
45 try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
46 let providers = drop.dropSession.items.map(\.itemProvider)
47 let files = DroppedFiles()
48 let group = DispatchGroup()
49 for (index, provider) in providers.enumerated() {
50 guard let type = provider.registeredContentTypes.first(where: { $0.conforms(to: .data) }) else { continue }
51 group.enter()
52 _ = provider.loadFileRepresentation(for: type, openInPlace: false) { url, _, _ in
53 defer { group.leave() }
54 guard let url else { return }
55 // Each in a folder of its own, so two drops of the same name stay apart.
56 let target = folder.appendingPathComponent("\(index)").appendingPathComponent(url.lastPathComponent)
57 try? FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
58 if (try? FileManager.default.copyItem(at: url, to: target)) != nil { files.add(target, at: index) }
59 }
60 }
61 group.notify(queue: .main) { [weak self] in
62 let dropped = files.inOrder
63 if !dropped.isEmpty { _ = self?.onFiles?(dropped) }
64 }
65 }
66}
67
68/// Files copied out of a drop's item providers, which call back on their own queues.
69private final class DroppedFiles: @unchecked Sendable {
70 private let lock = NSLock()
71 private var files: [Int: URL] = [:]
72 func add(_ file: URL, at index: Int) { lock.withLock { files[index] = file } }
73 var inOrder: [URL] { lock.withLock { files.sorted { $0.key < $1.key }.map(\.value) } }
74}
75#endif
Sources/OrgstarMobile/MobileEditor.swift +19
@@ -95,6 +95,12 @@ final class MobileEditor: NSObject, DocumentBuffer {
9595 var onColumnView: ((ColumnView.View) -> Void)?
9696 /// Commands the app runs, as `app.clock.in`.
9797 var onAppCommand: ((String) -> Void)?
98 /// Where paste looks for an image; scripts checking the app set another.
99 static var pasteboard = UIPasteboard.general
100 /// Files dropped at the caret; nil leaves them to the text view.
101 var onFiles: (([URL]) -> Void)?
102 /// An image pasted at the caret, with its extension (`yank-media`).
103 var onImage: ((Data, String) -> Void)?
98104 /// Tags used across the workspace, for completion.
99105 var knownTags: @Sendable () -> [String] = { [] }
100106
@@ -171,6 +177,19 @@ final class MobileEditor: NSObject, DocumentBuffer {
171177 return handleKey(key)
172178 }
173179 view.onLayout = { [weak self] in self?.viewResized() }
180 view.onFiles = { [weak self, weak view] files in
181 guard let self, let onFiles else { return false }
182 if let view { focus(view) }
183 onFiles(files)
184 return true
185 }
186 view.onImage = { [weak self, weak view] data, ext in
187 guard let self, let onImage else { return false }
188 if let view { focus(view) }
189 onImage(data, ext)
190 return true
191 }
192 view.textDropDelegate = view
174193 view.isEditable = editable
175194 view.autocorrectionType = .no
176195 view.autocapitalizationType = .none
Sources/OrgstarMobile/MobileFragments.swift +3
@@ -36,6 +36,9 @@ final class FragmentStyle: @unchecked Sendable {
3636/// A text view that offers hardware-keyboard presses to the editor's keymap first.
3737final class KeyedTextView: UITextView {
3838 var keyHandler: ((UIKey) -> Bool)?
39 /// Files dropped and an image pasted; each returns whether it took them.
40 var onFiles: (([URL]) -> Bool)?
41 var onImage: ((Data, String) -> Bool)?
3942 /// Keys the editor took, whose release the text system doesn't see. Optional: made by
4043 /// UIKit's `init(usingTextLayoutManager:)`, the view skips Swift's default values.
4144 private var handled: Set<UIKeyboardHIDUsage>?
Sources/OrgstarMobile/OrgstarMobileApp.swift +6
@@ -262,6 +262,12 @@ struct RootView: View {
262262 takeShared()
263263 // Development: `ORGSTAR_ROOT` adds a folder at launch, as on the Mac.
264264 if let root = ProcessInfo.processInfo.environment["ORGSTAR_ROOT"] { try? await workspace.addRoot(URL(fileURLWithPath: root)) }
265 // `ORGSTAR_PASTE_IMAGE`: paste takes this PNG from a pasteboard of the app's own.
266 if let image = ProcessInfo.processInfo.environment["ORGSTAR_PASTE_IMAGE"], let data = try? Data(contentsOf: URL(fileURLWithPath: image)),
267 let pasteboard = UIPasteboard(name: UIPasteboard.Name("orgstar-check"), create: true) {
268 pasteboard.setData(data, forPasteboardType: "public.png")
269 MobileEditor.pasteboard = pasteboard
270 }
265271 workspace.startWatching()
266272 await workspace.refresh()
267273 }
Tests/OrgAppTests/EmacsImportTests.swift +13
@@ -184,6 +184,19 @@ struct EmacsImportTests {
184184 #expect(s["org-icalendar-combined-agenda-file"] == .string("~/cal/org.ics"))
185185 }
186186
187 @Test func readsYankSettings() throws {
188 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-import-\(UUID().uuidString)")
189 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
190 defer { try? FileManager.default.removeItem(at: folder) }
191 try #"""
192 (setq org-yank-image-save-method "images/"
193 org-yank-dnd-method 'attach)
194 """#.write(to: folder.appendingPathComponent("init.el"), atomically: true, encoding: .utf8)
195 let s = settings(EmacsImport.scan(EmacsImport.files(in: folder)))
196 #expect(s["org-yank-image-save-method"] == .string("images/"))
197 #expect(s["org-yank-dnd-method"] == .string("attach"))
198 }
199
187200 @Test func readsLiterateConfig() throws {
188201 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-import-\(UUID().uuidString)")
189202 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
docs/manual/guide/09-links.org +31 −3
@@ -342,9 +342,37 @@ to a file ending in =.png=, =.jpg=, =.jpeg=, =.gif=, =.svg=, =.webp=, =.tif=, =.
342342[[./photo.jpg]]
343343#+END_SRC
344344
345Relative paths are resolved against the file's folder. =attachment:= links are not
346shown as images. The link text is hidden while the image is shown, except on the line
347that holds the caret.
345Relative paths are resolved against the file's folder, and =attachment:= links against the
346entry's attachment folder. The link text is hidden while the image is shown, except on the
347line that holds the caret, where the image is drawn under the link.
348
349** Pasting and dropping images
350
351Paste (⌘V, or Edit ▸ Paste on iOS) with an image on the clipboard and no text runs
352=yank-media=, as in Emacs 29 and later: the image is saved as =org-yank-image-save-method=
353says and a link to it is inserted at the caret. M-x =yank-media= does the same on the Mac.
354
355| =org-yank-image-save-method= | Where the image goes | Link |
356|------------------------------+--------------------------------------------------------------------------+-------------------------|
357| =attach= (the default) | The entry's attachment folder, as =org-attach-attach= puts it | =[[attachment:NAME]]= |
358| a folder, such as ="images/"= | That folder, relative to the file's folder unless absolute; made if missing | =[[file:images/NAME]]= |
359
360The name is Org's: =clipboard-= and the time, as in =clipboard-20261011T232238.png=; a
361second image in the same second gets =-2=. PNG, JPEG and GIF are saved as they are, and
362other image types as PNG. Before the first heading, =attach= gives the file a file-level
363=ID=, as Emacs does.
364
365Files dropped on the editor on the Mac, or pasted after copying them in Finder, are handled
366as =org-yank-dnd-method= says: =attach= copies them into the entry's attachment folder (an
367image goes to the =org-yank-image-save-method= folder when that is a folder), =file-link=
368links to them where they are, =open= opens them, and =ask=, the default, asks which. An
369image dragged in without a file, such as one from a browser, is pasted as above. On iOS,
370dropped files are always attached, since what a drop hands over is a copy. Attach Photo or
371Video… and Take Photo… also insert their links at the caret.
372
373Two things differ from Emacs, so that a pasted image shows at once: the link has no
374description (Org writes =[[attachment:NAME][NAME]]=, which inline display skips), and it
375goes on a line of its own, breaking the line around the caret when it holds text.
348376
349377** Remote images
350378
docs/manual/guide/13-configuration.org +5
@@ -171,6 +171,7 @@ These settings have no control in the Settings window. Some are in the View menu
171171| =org-timer-format=, =org-timer-default-timer= | |
172172| =org-roam-directory=, =org-roam-dailies-directory=, =org-roam-dailies-file=, =org-roam-dailies-head=, =org-roam-dailies-entry= | |
173173| =org-attach-id-dir=, =org-attach-use-inheritance= | |
174| =org-yank-image-save-method=, =org-yank-dnd-method= | |
174175| =org-crypt-tag-matcher= | |
175176| =org-agenda-start-on-weekday= | |
176177| =org-deadline-warning-days= | |
@@ -232,6 +233,8 @@ A key you remove from the file goes back to its default. A key that isn't in the
232233| =org-timer-default-timer= | string | ="0"= | The countdown Set Countdown Timer… offers, in minutes or =h:mm:ss=; ="0"= offers none. Mirrors =org-timer-default-timer=. |
233234| =org-attach-id-dir= | string | ="data/"= | The folder ID-based attachment folders go in, relative to the org file's folder unless absolute. See [[file:04-outlines.org][Outlines]]. Mirrors =org-attach-id-dir=. |
234235| =org-attach-use-inheritance= | string | ="selective"= | Whether attachment folders come from an ancestor's =DIR= or =ID=: =selective=, ="t"= or ="nil"=. Mirrors =org-attach-use-inheritance=. |
236| =org-yank-image-save-method= | string | ="attach"= | Where a pasted image goes: =attach= for the entry's attachment folder, or a folder, relative to the org file's folder unless absolute. See [[file:09-links.org][Links]]. Mirrors =org-yank-image-save-method=. |
237| =org-yank-dnd-method= | string | ="ask"= | What dropping files on the editor does: =ask=, =attach=, =open= or =file-link=. See [[file:09-links.org][Links]]. Mirrors =org-yank-dnd-method=. |
235238| =org-crypt-tag-matcher= | string | ="crypt"= | The tag Encrypt Tagged Entries… encrypts. A single tag. See [[file:04-outlines.org][Outlines]]. Mirrors =org-crypt-tag-matcher=. |
236239| =org-startup-indented= | boolean | =true= | Indent bodies under their headings, as =org-indent-mode=. =#+STARTUP: indent= / =noindent= override it. Mirrors =org-startup-indented=. |
237240| =org-hide-leading-stars= | boolean | =false= | Show only a heading's last star, without indentation. =#+STARTUP: hidestars= / =showstars= override it. Mirrors =org-hide-leading-stars=. |
@@ -601,6 +604,8 @@ Only variables whose names start with =org-=, =appt-=, =display-line-numbers=, =
601604| =org-timer-format=, =org-timer-default-timer= | The same keys; a number becomes a string |
602605| =org-attach-id-dir= | The same key, when the value is a string or an =expand-file-name= form |
603606| =org-attach-use-inheritance= | =selective=, or =t= / =nil= as ="t"= / ="nil"= |
607| =org-yank-image-save-method= | =attach=, or a folder name |
608| =org-yank-dnd-method= | =ask=, =attach=, =open= or =file-link= |
604609| =org-crypt-tag-matcher= | The same key, when the value is a single tag |
605610| =org-archive-location= | The same key, when the value is a =file::heading= string |
606611| =org-structure-template-alist= | =[org-structure-template-alist]=: each =("key" . "type")= entry that isn't one of Org's, from =setq= or =(add-to-list 'org-structure-template-alist …)= |
docs/manual/guide/14-ios.org +2 −2
@@ -155,7 +155,7 @@ Incremental Search is in Commands, and on =C-s= and =C-r= with a hardware keyboa
155155
156156The org-timer commands are in Commands; a running timer shows above the text. See [[file:06-dates-and-clocking.org][Dates and clocking]].
157157
158More ▸ Attachments has the org-attach commands and Attach Photo or Video…; files shared to orgstar can be attached to an entry. See [[file:04-outlines.org][Outlines]].
158More ▸ Attachments has the org-attach commands, Attach Photo or Video… and Take Photo…, which insert the photo's link at the caret; files shared to orgstar can be attached to an entry. Pasting an image and dropping files on the editor attach them and link them at the caret. See [[file:04-outlines.org][Outlines]] and [[file:09-links.org][Links]].
159159
160160More ▸ Encryption has the org-crypt commands; see [[file:04-outlines.org][Outlines]]. A remembered passphrase is used after Face ID, Touch ID or the device passcode.
161161
@@ -405,7 +405,7 @@ These settings from =config.toml= apply on iOS:
405405- =org-log-done=, =org-log-reschedule=, =org-log-redeadline=, =org-log-into-drawer=
406406- =org-enforce-todo-dependencies=, =org-enforce-todo-checkbox-dependencies=, =org-track-ordered-property-with-tag=, =org-agenda-dim-blocked-tasks=
407407- =org-roam-directory=, =org-roam-dailies-directory=, =org-roam-dailies-file=, =org-roam-dailies-head=, =org-roam-dailies-entry=
408- =org-crypt-tag-matcher=, =org-attach-id-dir=, =org-attach-use-inheritance=, =org-timer-format=, =org-timer-default-timer=
408- =org-crypt-tag-matcher=, =org-attach-id-dir=, =org-attach-use-inheritance=, =org-yank-image-save-method=, =org-timer-format=, =org-timer-default-timer=
409409- =org-archive-location=, =[org-structure-template-alist]=
410410- =org-use-tag-inheritance=, =org-tags-exclude-from-inheritance=, =org-tag-alist=
411411- =org-use-speed-commands=, with a hardware keyboard
ios/Orgstar/Info.plist +2
@@ -46,6 +46,8 @@
4646 <string>public.app-category.productivity</string>
4747 <key>NSCalendarsFullAccessUsageDescription</key>
4848 <string>The agenda shows your calendar events alongside your Org entries. orgstar changes your calendars only when you edit an event or add an entry to one.</string>
49 <key>NSCameraUsageDescription</key>
50 <string>Photos you take from the editor are saved with your notes and linked where the caret is.</string>
4951 <key>NSFaceIDUsageDescription</key>
5052 <string>Face ID unlocks the passphrase of encrypted entries you asked orgstar to remember.</string>
5153 <key>NSRemindersFullAccessUsageDescription</key>
l10n/Localizable.xcstrings +20
@@ -2312,6 +2312,16 @@
23122312 }
23132313 }
23142314 },
2315 "Habits only today": {
2316 "localizations": {
2317 "de": {
2318 "stringUnit": {
2319 "state": "translated",
2320 "value": "Gewohnheiten nur heute"
2321 }
2322 }
2323 }
2324 },
23152325 "Headings": {
23162326 "localizations": {
23172327 "de": {
@@ -4783,6 +4793,16 @@
47834793 }
47844794 }
47854795 },
4796 "Take Photo…": {
4797 "localizations": {
4798 "de": {
4799 "stringUnit": {
4800 "state": "translated",
4801 "value": "Foto aufnehmen …"
4802 }
4803 }
4804 }
4805 },
47864806 "Template": {
47874807 "localizations": {
47884808 "de": {
scripts/build-ios-app.sh +2
@@ -53,6 +53,8 @@ cat > "$app/Info.plist" <<PLIST
5353 <array><string>iPhoneSimulator</string></array>
5454 <key>MinimumOSVersion</key>
5555 <string>26.0</string>
56 <key>NSCameraUsageDescription</key>
57 <string>Photos you take from the editor are saved with your notes and linked where the caret is.</string>
5658 <key>NSFaceIDUsageDescription</key>
5759 <string>Face ID unlocks the passphrase of encrypted entries you asked orgstar to remember.</string>
5860 <key>NSCalendarsFullAccessUsageDescription</key>