Commit 1d52f06a76

1d52f06a761bd8eec3484c8581b923ac3b330d31

parent: 0c3d86f109

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-14 04:16 UTC

org-emphasize, with ⌘B, ⌘I and ⌘U in the Mac preset and key bar buttons on iOS

org-emphasize as Org 9.8.7 has it: with a selection, wraps it in the chosen
marker after stripping any marker pair it has; without one, inserts a pair
with the caret between; SPC removes emphasis; a space is added before or
after where the neighbouring character isn't in org-emphasis-regexp-components.
Checked against Emacs over ten texts and eight markers, caret included.

Emphasize… is C-c C-x C-f in the Emacs preset (and so in Doom's states).
Each marker is also a command of its own (org.emphasize.bold and so on); the
Mac preset binds ⌘B, ⌘I and ⌘U, and the iOS key bar has Bold, Italic and Code.

Closes #77

Layout: unified · split

Sources/OrgCore/Commands/Command.swift +1
@@ -344,6 +344,7 @@ public enum Commands {
344 CopySubtree(cut: false), CopySubtree(cut: true), CloneSubtree(), SortEntries(), InsertStructureTemplate(), EditSpecial(), TableEditField(), TangleCommand(.all), TangleCommand(.block), TangleCommand(.target), 344 CopySubtree(cut: false), CopySubtree(cut: true), CloneSubtree(), SortEntries(), InsertStructureTemplate(), EditSpecial(), TableEditField(), TangleCommand(.all), TangleCommand(.block), TangleCommand(.target),
345 UpdateDynamicBlock(), ClockReportTable(), SetEffort(), CtrlCCtrlC(), EvaluateTimeRange(), FootnoteAction(), FootnoteAction(special: true), TableEvalFormula(named: false), TableEvalFormula(named: true), SortTableLines(), TransposeTable(), GotoHeading(), SparseTreeCommand(), SetPriority(), SetPriority(value: "A"), SetPriority(value: "B"), SetPriority(value: "C"), SetPriority(value: " "), ReadAndSetProperty(), DeleteProperty(), DeleteProperty(globally: true), PropertyAction(), NextAllowedValue(previous: false), NextAllowedValue(previous: true), InsertColumnView(), ShowColumnView(), ShowColumnView(global: true), ToggleArchiveTag(), ArchiveToSibling(), ToggleOrderedProperty(), 345 UpdateDynamicBlock(), ClockReportTable(), SetEffort(), CtrlCCtrlC(), EvaluateTimeRange(), FootnoteAction(), FootnoteAction(special: true), TableEvalFormula(named: false), TableEvalFormula(named: true), SortTableLines(), TransposeTable(), GotoHeading(), SparseTreeCommand(), SetPriority(), SetPriority(value: "A"), SetPriority(value: "B"), SetPriority(value: "C"), SetPriority(value: " "), ReadAndSetProperty(), DeleteProperty(), DeleteProperty(globally: true), PropertyAction(), NextAllowedValue(previous: false), NextAllowedValue(previous: true), InsertColumnView(), ShowColumnView(), ShowColumnView(global: true), ToggleArchiveTag(), ArchiveToSibling(), ToggleOrderedProperty(),
346 InsertDrawer(), DragElement(forward: true), DragElement(forward: false), CycleBullet(previous: false), CycleBullet(previous: true), 346 InsertDrawer(), DragElement(forward: true), DragElement(forward: false), CycleBullet(previous: false), CycleBullet(previous: true),
347 Emphasize(), Emphasize(marker: "*"), Emphasize(marker: "/"), Emphasize(marker: "_"), Emphasize(marker: "="), Emphasize(marker: "~"), Emphasize(marker: "+"),
347 ] 348 ]
348 349
349 public static var everything: [any OrgCommand] { all + TableCommand.Action.allCases.map(TableCommand.init) } 350 public static var everything: [any OrgCommand] { all + TableCommand.Action.allCases.map(TableCommand.init) }
Sources/OrgCore/Commands/Emphasis.swift added +63
@@ -0,0 +1,63 @@
1import Foundation
2
3/// `org-emphasize`: wraps the selection in an emphasis marker, replacing one it already has, or
4/// with no selection inserts a pair and puts the caret between. A space removes the marker.
5/// `marker` set is the command for one marker, as the Mac preset's ⌘B binds it.
6public struct Emphasize: OrgCommand {
7 let marker: Character?
8 public init(marker: Character? = nil) { self.marker = marker }
9
10 /// `org-emphasis-alist`'s markers, and the id and title of each one's own command.
11 static let markers: [(marker: Character, name: String, title: String)] = [
12 ("*", "bold", "Bold"), ("/", "italic", "Italic"), ("_", "underline", "Underline"),
13 ("=", "verbatim", "Verbatim"), ("~", "code", "Code"), ("+", "strike-through", "Strike-Through"),
14 ]
15 /// `org-emphasis-regexp-components`: what may come before and after a marker.
16 static let before: Set<Character> = ["-", "(", "'", "\"", "{", "\n"]
17 static let after: Set<Character> = ["-", ".", ",", ":", "!", "?", ";", "'", "\"", ")", "}", "\\", "[", "\n"]
18
19 public var id: String { marker.flatMap { m in Self.markers.first { $0.marker == m } }.map { "org.emphasize.\($0.name)" } ?? "org.emphasize" }
20 public var title: String { marker.flatMap { m in Self.markers.first { $0.marker == m } }.map(\.title) ?? "Emphasize…" }
21 public func applies(in context: EditContext) -> Bool { true }
22
23 public func run(in context: EditContext) -> CommandStep {
24 let answer: Character
25 if let marker {
26 answer = marker
27 } else if let given = context.answers["emphasis"]?.first {
28 answer = given
29 } else {
30 let items = Self.markers.map { FastSelection.Item.option(key: $0.marker, name: $0.name) } + [.option(key: " ", name: "remove")]
31 let message = "Emphasis marker or tag: [\(String(Self.markers.map(\.marker)))]"
32 return .prompt(Prompt(key: "emphasis", message: message, fast: FastSelection(items: items, multiple: false)))
33 }
34 guard answer == " " || Self.markers.contains(where: { $0.marker == answer }) else {
35 return .failed("No such emphasis marker: \"\(answer)\"")
36 }
37 let text = context.text as NSString
38 let selection = context.selection.first ?? context.caret..<context.caret
39 let move = selection.isEmpty
40 var inner = text.substring(with: NSRange(selection))
41 // A selection already emphasized loses its markers first.
42 while inner.count > 1, let first = inner.first, inner.last == first, Self.markers.contains(where: { $0.marker == first }) {
43 inner = String(inner.dropFirst().dropLast())
44 }
45 let marker = answer == " " ? "" : String(answer)
46 let string = marker + inner + marker
47 func char(at offset: Int) -> Character? {
48 guard offset >= 0, offset < text.length else { return nil }
49 return Character(text.substring(with: text.rangeOfComposedCharacterSequence(at: offset)))
50 }
51 let previous = char(at: selection.lowerBound - 1)
52 let next = char(at: selection.upperBound)
53 let lead = previous.map { $0.isWhitespace || Self.before.contains($0) } ?? true ? "" : " "
54 let trail = next.map { $0.isWhitespace || Self.after.contains($0) } ?? true ? "" : " "
55 let start = selection.lowerBound + lead.utf16.count
56 let caret = move && answer != " " ? start + string.utf16.count - 1 : start + string.utf16.count
57 return .commit(EditResult(
58 baseRevision: context.revision,
59 edits: [TextEdit(range: selection, replacement: lead + string + trail)],
60 selection: [caret..<caret]
61 ))
62 }
63}
Sources/OrgCore/Keymap/PresetEmacs.swift +3
@@ -194,6 +194,9 @@ extension KeymapPreset {
194 keys = "C-c C-x o" 194 keys = "C-c C-x o"
195 command = "org.property.toggle-ordered" 195 command = "org.property.toggle-ordered"
196 [[bind]] 196 [[bind]]
197 keys = "C-c C-x C-f"
198 command = "org.emphasize"
199 [[bind]]
197 keys = "C-c C-x C-v" 200 keys = "C-c C-x C-v"
198 command = "org.toggle-inline-images" 201 command = "org.toggle-inline-images"
199 [[bind]] 202 [[bind]]
Sources/OrgCore/Keymap/PresetMac.swift +9
@@ -211,6 +211,15 @@ extension KeymapPreset {
211 keys = "s-k" 211 keys = "s-k"
212 command = "org.link.insert" 212 command = "org.link.insert"
213 [[bind]] 213 [[bind]]
214 keys = "s-b"
215 command = "org.emphasize.bold"
216 [[bind]]
217 keys = "s-i"
218 command = "org.emphasize.italic"
219 [[bind]]
220 keys = "s-u"
221 command = "org.emphasize.underline"
222 [[bind]]
214 keys = "C-s-o" 223 keys = "C-s-o"
215 command = "org.link.open" 224 command = "org.link.open"
216 [[bind]] 225 [[bind]]
Sources/OrgstarMobile/EditorScreen.swift +10
@@ -662,6 +662,13 @@ struct KeyBar: View {
662 ("Open link", "link", "C-c C-o"), 662 ("Open link", "link", "C-c C-o"),
663 ] 663 ]
664 664
665 /// Emphasis for the selection, or a pair of markers with the caret between.
666 private static let emphasis: [(label: String, symbol: String, command: String)] = [
667 ("Bold", "bold", "org.emphasize.bold"),
668 ("Italic", "italic", "org.emphasize.italic"),
669 ("Code", "chevron.left.forwardslash.chevron.right", "org.emphasize.code"),
670 ]
671
665 var body: some View { 672 var body: some View {
666 ScrollView(.horizontal, showsIndicators: false) { 673 ScrollView(.horizontal, showsIndicators: false) {
667 HStack(spacing: 4) { 674 HStack(spacing: 4) {
@@ -674,6 +681,9 @@ struct KeyBar: View {
674 } 681 }
675 .accessibilityLabel(key.label) 682 .accessibilityLabel(key.label)
676 } 683 }
684 ForEach(Self.emphasis, id: \.command) { item in
685 Button(item.label, systemImage: item.symbol) { editor.run(item.command) }
686 }
677 Button("Hide keyboard", systemImage: "keyboard.chevron.compact.down") { editor.textView.resignFirstResponder() } 687 Button("Hide keyboard", systemImage: "keyboard.chevron.compact.down") { editor.textView.resignFirstResponder() }
678 } 688 }
679 .labelStyle(.iconOnly) 689 .labelStyle(.iconOnly)
Tests/OrgCoreTests/EmphasizeTests.swift added +67
@@ -0,0 +1,67 @@
1import Foundation
2import Testing
3@testable import OrgCore
4
5struct EmphasizeTests {
6 static let oracle = ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil
7
8 func run(_ text: String, _ selection: Range<Int>, _ marker: String) -> (text: String, caret: Int, failure: String?) {
9 let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [selection], answers: ["emphasis": marker])
10 switch Emphasize().run(in: context) {
11 case .commit(let result):
12 var new = text
13 for edit in result.edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) { new = edit.apply(to: new) }
14 return (new, result.selection?.first?.lowerBound ?? selection.lowerBound, nil)
15 case .failed(let message): return (text, selection.lowerBound, message)
16 default: return (text, selection.lowerBound, "unexpected")
17 }
18 }
19
20 @Test(.enabled(if: oracle))
21 func emphasizesLikeOrg() throws {
22 let cases: [(String, Range<Int>)] = [
23 ("Hello world\n", 6..<11), ("Hello world\n", 5..<5), ("Hello world\n", 6..<6), ("Hello world\n", 0..<0),
24 ("Hello *world* again\n", 6..<13), ("Hello world\n", 0..<5), ("say (it) now\n", 5..<7), ("abc", 3..<3),
25 ("one-two\n", 4..<7), ("a**b\n", 1..<3),
26 ]
27 let markers = ["*", "/", "_", "=", "~", "+", " ", "q"]
28 var oracleCases: [EmacsOracle.Case] = []
29 var ours: [(text: String, caret: Int, failure: String?)] = []
30 for (text, selection) in cases {
31 for marker in markers {
32 let char = marker == " " ? "?\\s" : "?\(marker)"
33 let form = selection.isEmpty
34 ? "(org-emphasize \(char))"
35 : "(let ((transient-mark-mode t)) (push-mark \(selection.lowerBound + 1) t t) (org-emphasize \(char)))"
36 oracleCases.append(EmacsOracle.Case(text: text, point: selection.upperBound + 1, form: form))
37 ours.append(run(text, selection, marker))
38 }
39 }
40 for (i, theirs) in try EmacsOracle.run(oracleCases).enumerated() {
41 let label = "\(oracleCases[i].form) on \(oracleCases[i].text.debugDescription)"
42 #expect((ours[i].failure != nil) == !theirs.error.isEmpty, "\(label): \(ours[i].failure ?? "") vs \(theirs.error)")
43 guard theirs.error.isEmpty else { continue }
44 #expect(ours[i].text == theirs.text, "\(label)")
45 #expect(ours[i].caret == theirs.point - 1, "\(label): caret")
46 }
47 }
48
49 @Test func asksForTheMarker() {
50 let text = "word\n"
51 let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [0..<4])
52 guard case .prompt(let prompt) = Emphasize().run(in: context) else { Issue.record("no prompt"); return }
53 #expect(prompt.key == "emphasis")
54 #expect(prompt.fast?.items.count == 7)
55 }
56
57 @Test func fixedMarkers() {
58 let text = "word\n"
59 let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [0..<4])
60 guard case .commit(let result) = Emphasize(marker: "*").run(in: context) else { Issue.record("no edit"); return }
61 #expect(result.edits.first.map { $0.apply(to: text) } == "*word*\n")
62 #expect(Emphasize(marker: "*").id == "org.emphasize.bold")
63 #expect(Emphasize(marker: "/").id == "org.emphasize.italic")
64 #expect(Emphasize(marker: "_").id == "org.emphasize.underline")
65 #expect(Emphasize(marker: "~").id == "org.emphasize.code")
66 }
67}
docs/manual/guide/02-the-editor.org +6
@@ -32,6 +32,12 @@ The two Org options are in Settings ▸ Editing as "Emacs hides emphasis markers
32 32
33Colours come from the theme and follow the system's light or dark appearance. The font, size, line spacing and text width are in Settings ▸ Appearance; colours are set in =config.toml=. See [[file:13-configuration.org][Configuration]]. The font should be monospaced, since tags and tables line up by columns. A body font for prose can be set beside it, as =mixed-pitch-mode= does in Emacs: prose and headings use it, and tables, code, dates, tags, drawers and the start of each line keep the monospaced font. 33Colours come from the theme and follow the system's light or dark appearance. The font, size, line spacing and text width are in Settings ▸ Appearance; colours are set in =config.toml=. See [[file:13-configuration.org][Configuration]]. The font should be monospaced, since tags and tables line up by columns. A body font for prose can be set beside it, as =mixed-pitch-mode= does in Emacs: prose and headings use it, and tables, code, dates, tags, drawers and the start of each line keep the monospaced font.
34 34
35** Adding emphasis
36
37Emphasize… (=C-c C-x C-f= in the Emacs and Doom presets, =org-emphasize=) asks for a marker: =*= bold, =/= italic, =_= underline, === verbatim, =~= code, =+= strike-through, or =SPC= to remove emphasis. With a selection it wraps the selection in the marker, replacing one the selection already has. Without one it inserts a pair of markers with the caret between them. A space goes before or after the markers where the text next to them couldn't border emphasis, as Org adds it.
38
39The Mac preset binds =⌘B=, =⌘I= and =⌘U= to bold, italic and underline. Each marker is also a command of its own in the palette (Bold, Italic, Underline, Verbatim, Code, Strike-Through), for binding in =keymap.toml=; see [[file:03-keys.org][Keys and commands]]. On iOS the key bar has Bold, Italic and Code.
40
35** Indentation and stars 41** Indentation and stars
36 42
37Org files display as =org-indent-mode= shows them, by default: each heading's body is indented to start one column past its stars, all stars but the last are hidden, and a wrapped heading title continues under the title. The indentation is display only; the file keeps its text at the left margin. 43Org files display as =org-indent-mode= shows them, by default: each heading's body is indented to start one column past its stars, all stars but the last are hidden, and a wrapped heading title continues under the title. The indentation is display only; the file keeps its text at the left margin.
docs/manual/guide/03-keys.org +5
@@ -951,6 +951,10 @@ When a key appears in several rows, it runs the command whose condition holds at
951| Command | Emacs | Mac | Doom | What it does | 951| Command | Emacs | Mac | Doom | What it does |
952|-+-+-+-+-| 952|-+-+-+-+-|
953| Open Link (=org.link.open=) | =C-c C-o= | =⌃⌘O= | — | Follows the link or timestamp at the caret (=org-open-at-point=). | 953| Open Link (=org.link.open=) | =C-c C-o= | =⌃⌘O= | — | Follows the link or timestamp at the caret (=org-open-at-point=). |
954| Emphasize… (=org.emphasize=) | =C-c C-x C-f= | — | — | Asks for a marker and wraps the selection in it, or inserts a pair with the caret between (=org-emphasize=). |
955| Bold (=org.emphasize.bold=) | — | =⌘B= | — | =org-emphasize= with =*=. |
956| Italic (=org.emphasize.italic=) | — | =⌘I= | — | =org-emphasize= with =/=. |
957| Underline (=org.emphasize.underline=) | — | =⌘U= | — | =org-emphasize= with =_=. |
954| Insert Link… (=org.link.insert=) | =C-c C-l= | =⌘K= | =SPC m l l= (N) | Asks for a link and description and inserts it, offering stored links (=org-insert-link=). | 958| Insert Link… (=org.link.insert=) | =C-c C-l= | =⌘K= | =SPC m l l= (N) | Asks for a link and description and inserts it, offering stored links (=org-insert-link=). |
955| Store Link (=org.link.store=) | =C-c l= | =⌃⌘L= | =SPC m l s= (N), =SPC n l= (N) | Stores a link to the current entry for a later Insert Link (=org-store-link=). | 959| Store Link (=org.link.store=) | =C-c l= | =⌃⌘L= | =SPC m l s= (N), =SPC n l= (N) | Stores a link to the current entry for a later Insert Link (=org-store-link=). |
956| Store ID Link (=org.id.store-link=) | — | — | =SPC m l i= (N) | Gives the entry an =ID= if needed and stores an =id:= link to it (=org-id-store-link=). | 960| Store ID Link (=org.id.store-link=) | — | — | =SPC m l i= (N) | Gives the entry an =ID= if needed and stores an =id:= link to it (=org-id-store-link=). |
@@ -1074,6 +1078,7 @@ No preset binds these. Run them from the palette or a menu, or bind them in =key
1074| Command | What it does | 1078| Command | What it does |
1075|-+-| 1079|-+-|
1076| Board (=app.board=) | Opens the Board window. Window ▸ Board, =⇧⌘B=. | 1080| Board (=app.board=) | Opens the Board window. Window ▸ Board, =⇧⌘B=. |
1081| Verbatim, Code, Strike-Through (=org.emphasize.verbatim=, =org.emphasize.code=, =org.emphasize.strike-through=) | =org-emphasize= with ===, =~= or =+=. |
1077| Cancel Running Task (=app.babel.cancel=) | Stops the src block that is running, or an export or table recalculation running in Emacs. Edit ▸ Cancel Running Task, =⌘.=. | 1082| Cancel Running Task (=app.babel.cancel=) | Stops the src block that is running, or an export or table recalculation running in Emacs. Edit ▸ Cancel Running Task, =⌘.=. |
1078| Edit Config File (=app.edit-config=) | Opens =config.toml= in the editor. =⌥⌘,=. | 1083| Edit Config File (=app.edit-config=) | Opens =config.toml= in the editor. =⌥⌘,=. |
1079| Import from Emacs… (=app.import-emacs=) | Opens Import from Emacs…. | 1084| Import from Emacs… (=app.import-emacs=) | Opens Import from Emacs…. |
docs/manual/guide/14-ios.org +1
@@ -134,6 +134,7 @@ A bar above the on-screen keyboard has buttons for Org's keys. Each does what it
134| Deadline | =C-c C-d= | 134| Deadline | =C-c C-d= |
135| Tags | =C-c C-q= | 135| Tags | =C-c C-q= |
136| Open link | =C-c C-o= | 136| Open link | =C-c C-o= |
137| Bold, Italic, Code | Emphasize with =*=, =/= or =~=: the selection, or a pair of markers with the caret between |
137| Hide keyboard | | 138| Hide keyboard | |
138 139
139** Commands 140** Commands