Commit 8f8f9a8c12

8f8f9a8c12170a956eedc8c5db4f319a9e7f7518

parent: 6236c2f7de

Verified · cmc

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

Proportional body font with fixed-pitch tables, code and tags

`[theme] body-font` (Settings ▸ Appearance ▸ Body text) sets a font for prose,
as Emacs's mixed-pitch-mode does: a family, or "system" for the system's
proportional font; empty keeps `font` throughout, as before. Tables, blocks,
verbatim and code, keyword, planning and drawer lines, timestamps and tags keep
the fixed-pitch font (Presentation.isFixedPitch), and so do a heading's stars
and a line's leading blanks, bullet and checkbox (fixedPitchPrefixes), so
org-indent's indentation, still counted in fixed-pitch columns, lines up. The
iOS editor and reader read the same setting.

Closes #74

Layout: unified · split

Sources/OrgApp/OrgPreferences.swift +1
@@ -66,6 +66,7 @@ public enum OrgPreferences {
66 public static func theme(_ colors: ThemeSpec, _ defaults: UserDefaults = .standard) -> ThemeSpec { 66 public static func theme(_ colors: ThemeSpec, _ defaults: UserDefaults = .standard) -> ThemeSpec {
67 var spec = colors 67 var spec = colors
68 spec.font = string("themeFont", defaults) 68 spec.font = string("themeFont", defaults)
69 spec.bodyFont = string("themeBodyFont", defaults)
69 spec.fontSize = integer("themeFontSize", defaults) 70 spec.fontSize = integer("themeFontSize", defaults)
70 spec.lineSpacing = integer("themeLineSpacing", defaults) 71 spec.lineSpacing = integer("themeLineSpacing", defaults)
71 spec.headingSizeStep = integer("themeHeadingStep", defaults) 72 spec.headingSizeStep = integer("themeHeadingStep", defaults)
Sources/OrgApp/UserConfig.swift +2
@@ -295,6 +295,8 @@ public enum UserConfig {
295 comment: "the grid's times as HHMM, separated by spaces", legacy: ""), 295 comment: "the grid's times as HHMM, separated by spaces", legacy: ""),
296 Setting(section: "theme", key: "font", defaultsKey: "themeFont", kind: .string, fallback: .string(""), 296 Setting(section: "theme", key: "font", defaultsKey: "themeFont", kind: .string, fallback: .string(""),
297 comment: "a monospaced font family; \"\" for the system's", legacy: ""), 297 comment: "a monospaced font family; \"\" for the system's", legacy: ""),
298 Setting(section: "theme", key: "body-font", defaultsKey: "themeBodyFont", kind: .string, fallback: .string(""),
299 comment: "a font family for prose, or \"system\"; tables, code, dates and tags keep the font above; \"\" for the font above throughout", legacy: ""),
298 Setting(section: "theme", key: "font-size", defaultsKey: "themeFontSize", kind: .integer, fallback: .integer(13), 300 Setting(section: "theme", key: "font-size", defaultsKey: "themeFontSize", kind: .integer, fallback: .integer(13),
299 comment: "points", legacy: ""), 301 comment: "points", legacy: ""),
300 Setting(section: "theme", key: "line-spacing", defaultsKey: "themeLineSpacing", kind: .integer, fallback: .integer(2), 302 Setting(section: "theme", key: "line-spacing", defaultsKey: "themeLineSpacing", kind: .integer, fallback: .integer(2),
Sources/OrgEditorAppKit/OrgEditor+Styling.swift +7 −1
@@ -43,6 +43,12 @@ extension OrgEditor {
43 } 43 }
44 if Presentation.excludesScripts(run.role) { scriptExclusions.append(run.range) } 44 if Presentation.excludesScripts(run.role) { scriptExclusions.append(run.range) }
45 } 45 }
46 if theme.mixedPitch {
47 for prefix in Presentation.fixedPitchPrefixes(storage.string as NSString, in: range) {
48 guard let clipped = clip(prefix, to: range) else { continue }
49 storage.addAttribute(.font, value: theme.fixedPitch(storage, clipped), range: clipped)
50 }
51 }
46 if !showMarkup, options.prettyEntities { prettify(range, in: storage, revealed: revealed, scriptExclusions: scriptExclusions) } 52 if !showMarkup, options.prettyEntities { prettify(range, in: storage, revealed: revealed, scriptExclusions: scriptExclusions) }
47 applyShrunk(range, in: storage) 53 applyShrunk(range, in: storage)
48 applyHighlights(range, in: storage) 54 applyHighlights(range, in: storage)
@@ -70,7 +76,7 @@ extension OrgEditor {
70 } 76 }
71 let size = theme.font.pointSize 77 let size = theme.font.pointSize
72 storage.addAttributes([ 78 storage.addAttributes([
73 .font: NSFont.monospacedSystemFont(ofSize: size * 0.7, weight: .regular), 79 .font: theme.mixedPitch ? theme.body.withSize(size * 0.7) : NSFont.monospacedSystemFont(ofSize: size * 0.7, weight: .regular),
74 .baselineOffset: (superscript ? 0.3 : -0.3) * size, 80 .baselineOffset: (superscript ? 0.3 : -0.3) * size,
75 ], range: NSRange(location: lineStart + body.lowerBound, length: body.count)) 81 ], range: NSRange(location: lineStart + body.lowerBound, length: body.count))
76 } 82 }
Sources/OrgEditorAppKit/OrgEditor.swift +1 −1
@@ -282,7 +282,7 @@ public final class OrgEditor: NSObject {
282 private func applyThemeToView() { 282 private func applyThemeToView() {
283 Theme.selection = theme.color("selection") ?? .selectedTextBackgroundColor 283 Theme.selection = theme.color("selection") ?? .selectedTextBackgroundColor
284 for view in orgTextViews { 284 for view in orgTextViews {
285 view.font = theme.font 285 view.font = theme.body
286 view.typingAttributes = theme.base 286 view.typingAttributes = theme.base
287 view.drawsBackground = true 287 view.drawsBackground = true
288 view.backgroundColor = theme.color("background") ?? .textBackgroundColor 288 view.backgroundColor = theme.color("background") ?? .textBackgroundColor
Sources/OrgEditorAppKit/Theme.swift +25 −4
@@ -6,7 +6,10 @@ import OrgPresentation
6@MainActor 6@MainActor
7struct Theme { 7struct Theme {
8 let spec: ThemeSpec 8 let spec: ThemeSpec
9 /// The fixed-pitch font: columns, tables, code and the rest of `Presentation.isFixedPitch`.
9 let font: NSFont 10 let font: NSFont
11 /// The font for prose; `font` unless the theme names a body font.
12 let body: NSFont
10 13
11 init(_ spec: ThemeSpec = .default) { 14 init(_ spec: ThemeSpec = .default) {
12 self.spec = spec 15 self.spec = spec
@@ -14,9 +17,24 @@ struct Theme {
14 font = spec.font.isEmpty ? NSFont.monospacedSystemFont(ofSize: size, weight: .regular) 17 font = spec.font.isEmpty ? NSFont.monospacedSystemFont(ofSize: size, weight: .regular)
15 : NSFontManager.shared.font(withFamily: spec.font, traits: [], weight: 5, size: size) 18 : NSFontManager.shared.font(withFamily: spec.font, traits: [], weight: 5, size: size)
16 ?? NSFont.monospacedSystemFont(ofSize: size, weight: .regular) 19 ?? NSFont.monospacedSystemFont(ofSize: size, weight: .regular)
20 body = switch spec.bodyFont {
21 case "": font
22 case "system": NSFont.systemFont(ofSize: size)
23 case let family: NSFontManager.shared.font(withFamily: family, traits: [], weight: 5, size: size) ?? font
24 }
17 Self.blockBackground = color("block-background") ?? .clear 25 Self.blockBackground = color("block-background") ?? .clear
18 } 26 }
19 27
28 /// Prose and fixed-pitch text use different fonts.
29 var mixedPitch: Bool { body != font }
30
31 /// The fixed-pitch font at the size and weight the text in `range` has.
32 func fixedPitch(_ storage: NSTextStorage, _ range: NSRange) -> NSFont {
33 let current = currentFont(storage, range)
34 let sized = font.withSize(current.pointSize)
35 return current.fontDescriptor.symbolicTraits.contains(.bold) ? NSFontManager.shared.convert(sized, toHaveTrait: .boldFontMask) : sized
36 }
37
20 /// A color that follows the appearance, or nil when the theme has none for `key`. 38 /// A color that follows the appearance, or nil when the theme has none for `key`.
21 func color(_ key: String) -> NSColor? { 39 func color(_ key: String) -> NSColor? {
22 // Editor colors are set for both appearances by the default theme; a key the theme 40 // Editor colors are set for both appearances by the default theme; a key the theme
@@ -43,7 +61,7 @@ struct Theme {
43 var foreground: NSColor { color("foreground") ?? .textColor } 61 var foreground: NSColor { color("foreground") ?? .textColor }
44 62
45 var base: [NSAttributedString.Key: Any] { 63 var base: [NSAttributedString.Key: Any] {
46 [.font: font, .foregroundColor: foreground, .paragraphStyle: paragraphStyle(firstLine: 0, wrapped: 0)] 64 [.font: body, .foregroundColor: foreground, .paragraphStyle: paragraphStyle(firstLine: 0, wrapped: 0)]
47 } 65 }
48 66
49 /// Width of one column of the monospaced font. 67 /// Width of one column of the monospaced font.
@@ -78,10 +96,13 @@ struct Theme {
78 func fg(_ key: String) { 96 func fg(_ key: String) {
79 if let color = color(key) { storage.addAttribute(.foregroundColor, value: color, range: range) } 97 if let color = color(key) { storage.addAttribute(.foregroundColor, value: color, range: range) }
80 } 98 }
99 if mixedPitch, Presentation.isFixedPitch(role) {
100 storage.addAttribute(.font, value: fixedPitch(storage, range), range: range)
101 }
81 switch role { 102 switch role {
82 case .heading(let level): 103 case .heading(let level):
83 let size = font.pointSize + CGFloat(max(0, spec.headingSizeStep) * max(0, 4 - level)) 104 let size = body.pointSize + CGFloat(max(0, spec.headingSizeStep) * max(0, 4 - level))
84 let heading = NSFontManager.shared.convert(font.withSize(size), toHaveTrait: .boldFontMask) 105 let heading = NSFontManager.shared.convert(body.withSize(size), toHaveTrait: .boldFontMask)
85 storage.addAttribute(.font, value: heading, range: range) 106 storage.addAttribute(.font, value: heading, range: range)
86 fg("heading-\(min(max(level, 1), 8))") 107 fg("heading-\(min(max(level, 1), 8))")
87 case .leadingStars: 108 case .leadingStars:
@@ -126,7 +147,7 @@ struct Theme {
126 } 147 }
127 148
128 private func currentFont(_ storage: NSTextStorage, _ range: NSRange) -> NSFont { 149 private func currentFont(_ storage: NSTextStorage, _ range: NSRange) -> NSFont {
129 storage.attribute(.font, at: range.location, effectiveRange: nil) as? NSFont ?? font 150 storage.attribute(.font, at: range.location, effectiveRange: nil) as? NSFont ?? body
130 } 151 }
131 152
132 private func bold(_ storage: NSTextStorage, _ range: NSRange) -> NSFont { 153 private func bold(_ storage: NSTextStorage, _ range: NSRange) -> NSFont {
Sources/OrgPresentation/Display.swift +57
@@ -92,6 +92,63 @@ extension Presentation {
92 return out 92 return out
93 } 93 }
94 94
95 /// Roles drawn in the fixed-pitch font when the body font is proportional, as Emacs's
96 /// mixed-pitch-mode keeps `mixed-pitch-fixed-pitch-faces`: text that lines up by column.
97 public static func isFixedPitch(_ role: StyleRole) -> Bool {
98 switch role {
99 case .table, .rule, .block, .blockDelimiter, .verbatim, .code, .inlineSource, .metadata, .keyword, .tags, .timestamp, .syntax: true
100 default: false
101 }
102 }
103
104 /// The start of each line in `range` that sets where its text begins, for the fixed-pitch
105 /// font under a proportional body: a heading's stars and space, and the leading blanks,
106 /// bullet and checkbox `hangingColumns` counts. org-indent's indentation is in columns of
107 /// the fixed-pitch font, so these keep text lined up under it.
108 public static func fixedPitchPrefixes(_ text: NSString, in range: Range<Int>) -> [Range<Int>] {
109 var out: [Range<Int>] = []
110 var location = range.lowerBound
111 while location < range.upperBound {
112 let line = text.lineRange(for: NSRange(location: location, length: 0))
113 guard line.length > 0 else { break }
114 location = NSMaxRange(line)
115 let content = text.substring(with: line)
116 let stars = content.prefix { $0 == "*" }.count
117 let length: Int
118 if stars > 0, content.dropFirst(stars).first == " " {
119 length = stars + 1
120 } else {
121 length = hangingPrefix(content).utf16.count
122 }
123 if length > 0 { out.append(line.location..<(line.location + length)) }
124 }
125 return out
126 }
127
128 /// The characters `hangingColumns` counts: leading blanks, then a bullet, its space and a
129 /// checkbox.
130 static func hangingPrefix(_ line: String) -> Substring {
131 let blanks = line.prefix { $0 == " " || $0 == "\t" }
132 let rest = line.dropFirst(blanks.count)
133 var bullet = 0
134 if let first = rest.first, first == "-" || first == "+" || (first == "*" && !blanks.isEmpty) {
135 bullet = 1
136 } else {
137 let digits = rest.prefix { $0.isASCII && $0.isNumber }
138 if !digits.isEmpty, let separator = rest.dropFirst(digits.count).first, separator == "." || separator == ")" {
139 bullet = digits.count + 1
140 }
141 }
142 guard bullet > 0, rest.dropFirst(bullet).first == " " else { return blanks }
143 var length = blanks.count + bullet + 1
144 let afterBullet = rest.dropFirst(bullet + 1)
145 if afterBullet.count >= 4, afterBullet.first == "[", "X x-".contains(afterBullet.dropFirst().first!),
146 afterBullet.dropFirst(2).first == "]", afterBullet.dropFirst(3).first == " " {
147 length += 4
148 }
149 return line.prefix(length)
150 }
151
95 /// Columns a wrapped continuation of `line` should start past the line's own start. 152 /// Columns a wrapped continuation of `line` should start past the line's own start.
96 public static func hangingColumns(_ line: String) -> Int { 153 public static func hangingColumns(_ line: String) -> Int {
97 var columns = 0 154 var columns = 0
Sources/OrgPresentation/ThemeSpec.swift +4 −1
@@ -38,6 +38,9 @@ public struct RGBA: Hashable, Sendable {
38public struct ThemeSpec: Equatable, Sendable { 38public struct ThemeSpec: Equatable, Sendable {
39 /// A font family; empty for the system's monospaced font. 39 /// A font family; empty for the system's monospaced font.
40 public var font = "" 40 public var font = ""
41 /// The font for prose: a family, `system` for the system's proportional font, or empty for
42 /// `font` throughout. Tables, code and other `Presentation.isFixedPitch` text keep `font`.
43 public var bodyFont = ""
41 public var fontSize = 13 44 public var fontSize = 13
42 /// Points between lines. 45 /// Points between lines.
43 public var lineSpacing = 2 46 public var lineSpacing = 2
@@ -182,7 +185,7 @@ public struct ThemeSpec: Equatable, Sendable {
182 // MARK: - Reading 185 // MARK: - Reading
183 186
184 /// Keys of `[theme]` that aren't colors; config.toml's settings handle them. 187 /// Keys of `[theme]` that aren't colors; config.toml's settings handle them.
185 public static let typeKeys: Set<String> = ["font", "font-size", "line-spacing", "heading-size-step", "theme-file"] 188 public static let typeKeys: Set<String> = ["font", "body-font", "font-size", "line-spacing", "heading-size-step", "theme-file"]
186 189
187 /// Whether a table holds theme colors. 190 /// Whether a table holds theme colors.
188 public static func isThemeTable(_ name: String) -> Bool { 191 public static func isThemeTable(_ name: String) -> Bool {
Sources/Orgstar/ContentView.swift +2
@@ -92,6 +92,7 @@ struct ContentView: View {
92 @AppStorage("showHiddenFiles") private var showHiddenFiles = true 92 @AppStorage("showHiddenFiles") private var showHiddenFiles = true
93 @AppStorage("ignoredFolders") private var ignoredFolders = ScanRules.defaultIgnoredFolders.sorted().joined(separator: " ") 93 @AppStorage("ignoredFolders") private var ignoredFolders = ScanRules.defaultIgnoredFolders.sorted().joined(separator: " ")
94 @AppStorage("themeFont") private var themeFont = "" 94 @AppStorage("themeFont") private var themeFont = ""
95 @AppStorage("themeBodyFont") private var themeBodyFont = ""
95 @AppStorage("themeFontSize") private var themeFontSize = 13 96 @AppStorage("themeFontSize") private var themeFontSize = 13
96 @AppStorage("themeLineSpacing") private var themeLineSpacing = 2 97 @AppStorage("themeLineSpacing") private var themeLineSpacing = 2
97 @AppStorage("themeHeadingStep") private var themeHeadingStep = 1 98 @AppStorage("themeHeadingStep") private var themeHeadingStep = 1
@@ -100,6 +101,7 @@ struct ContentView: View {
100 private var theme: ThemeSpec { 101 private var theme: ThemeSpec {
101 var spec = ConfigSync.shared.theme 102 var spec = ConfigSync.shared.theme
102 spec.font = themeFont 103 spec.font = themeFont
104 spec.bodyFont = themeBodyFont
103 spec.fontSize = themeFontSize 105 spec.fontSize = themeFontSize
104 spec.lineSpacing = themeLineSpacing 106 spec.lineSpacing = themeLineSpacing
105 spec.headingSizeStep = themeHeadingStep 107 spec.headingSizeStep = themeHeadingStep
Sources/Orgstar/OrgstarApp.swift +14 −1
@@ -621,10 +621,16 @@ struct SettingsView: View {
621 @AppStorage("settingsTab") private var tab = "general" 621 @AppStorage("settingsTab") private var tab = "general"
622 @AppStorage("showHiddenFiles") private var showHiddenFiles = true 622 @AppStorage("showHiddenFiles") private var showHiddenFiles = true
623 @AppStorage("themeFont") private var themeFont = "" 623 @AppStorage("themeFont") private var themeFont = ""
624 @AppStorage("themeBodyFont") private var themeBodyFont = ""
624 @AppStorage("themeFontSize") private var themeFontSize = 13 625 @AppStorage("themeFontSize") private var themeFontSize = 13
625 @AppStorage("themeLineSpacing") private var themeLineSpacing = 2 626 @AppStorage("themeLineSpacing") private var themeLineSpacing = 2
626 @AppStorage("themeHeadingStep") private var themeHeadingStep = 1 627 @AppStorage("themeHeadingStep") private var themeHeadingStep = 1
627 628
629 /// Installed font families that aren't monospaced, for body text.
630 private static let proportionalFamilies: [String] = NSFontManager.shared.availableFontFamilies.filter { family in
631 NSFontManager.shared.font(withFamily: family, traits: [], weight: 5, size: 13)?.isFixedPitch == false
632 }
633
628 /// Installed monospaced font families. 634 /// Installed monospaced font families.
629 private static let monospacedFamilies: [String] = NSFontManager.shared.availableFontFamilies.filter { family in 635 private static let monospacedFamilies: [String] = NSFontManager.shared.availableFontFamilies.filter { family in
630 NSFontManager.shared.font(withFamily: family, traits: [], weight: 5, size: 13)?.isFixedPitch == true 636 NSFontManager.shared.font(withFamily: family, traits: [], weight: 5, size: 13)?.isFixedPitch == true
@@ -775,11 +781,18 @@ struct SettingsView: View {
775 ForEach(Self.monospacedFamilies, id: \.self) { Text($0).tag($0) } 781 ForEach(Self.monospacedFamilies, id: \.self) { Text($0).tag($0) }
776 if !themeFont.isEmpty, !Self.monospacedFamilies.contains(themeFont) { Text(themeFont).tag(themeFont) } 782 if !themeFont.isEmpty, !Self.monospacedFamilies.contains(themeFont) { Text(themeFont).tag(themeFont) }
777 } 783 }
784 Picker("Body text", selection: $themeBodyFont) {
785 Text("Same as Font").tag("")
786 Text("System").tag("system")
787 Divider()
788 ForEach(Self.proportionalFamilies, id: \.self) { Text($0).tag($0) }
789 if !["", "system"].contains(themeBodyFont), !Self.proportionalFamilies.contains(themeBodyFont) { Text(themeBodyFont).tag(themeBodyFont) }
790 }
778 Stepper("Size: \(themeFontSize) pt", value: $themeFontSize, in: 8...36) 791 Stepper("Size: \(themeFontSize) pt", value: $themeFontSize, in: 8...36)
779 Stepper("Line spacing: \(themeLineSpacing) pt", value: $themeLineSpacing, in: 0...16) 792 Stepper("Line spacing: \(themeLineSpacing) pt", value: $themeLineSpacing, in: 0...16)
780 Stepper("Headings grow by \(themeHeadingStep) pt a level", value: $themeHeadingStep, in: 0...8) 793 Stepper("Headings grow by \(themeHeadingStep) pt a level", value: $themeHeadingStep, in: 0...8)
781 } footer: { 794 } footer: {
782 Text("Tags and tables line up in columns, so a monospaced font keeps them straight.") 795 Text("Tags and tables line up in columns, so Font should be monospaced. With a Body text font, prose uses it while tables, code, dates, tags and drawers keep Font.")
783 .settingsFooter() 796 .settingsFooter()
784 } 797 }
785 Section { 798 Section {
Sources/OrgstarMobile/MobileEditor+Styling.swift +9 −1
@@ -203,6 +203,14 @@ extension MobileEditor {
203 } 203 }
204 if Presentation.excludesScripts(run.role) { scriptExclusions.append(run.range) } 204 if Presentation.excludesScripts(run.role) { scriptExclusions.append(run.range) }
205 } 205 }
206 if theme.mixedPitch {
207 for prefix in Presentation.fixedPitchPrefixes(ns, in: whole) {
208 let clipped = NSIntersectionRange(NSRange(prefix), lines)
209 guard clipped.length > 0 else { continue }
210 let current = storage.attribute(.font, at: clipped.location, effectiveRange: nil) as? UIFont ?? theme.body
211 storage.addAttribute(.font, value: theme.fixedPitch(current), range: clipped)
212 }
213 }
206 if !showMarkup, options.prettyEntities { prettify(whole, in: storage, revealed: revealed, scriptExclusions: scriptExclusions) } 214 if !showMarkup, options.prettyEntities { prettify(whole, in: storage, revealed: revealed, scriptExclusions: scriptExclusions) }
207 applyShrunk(whole, in: storage) 215 applyShrunk(whole, in: storage)
208 applyImages(whole, in: storage, revealed: revealed) 216 applyImages(whole, in: storage, revealed: revealed)
@@ -238,7 +246,7 @@ extension MobileEditor {
238 } 246 }
239 let size = theme.font.pointSize 247 let size = theme.font.pointSize
240 storage.addAttributes([ 248 storage.addAttributes([
241 .font: theme.font.withSize(size * 0.7), 249 .font: theme.body.withSize(size * 0.7),
242 .baselineOffset: (superscript ? 0.3 : -0.3) * size, 250 .baselineOffset: (superscript ? 0.3 : -0.3) * size,
243 ], range: NSRange(location: lineStart + body.lowerBound, length: body.count)) 251 ], range: NSRange(location: lineStart + body.lowerBound, length: body.count))
244 } 252 }
Sources/OrgstarMobile/MobileEditor.swift +1 −1
@@ -32,7 +32,7 @@ final class MobileEditor: NSObject, DocumentBuffer {
32 get { theme.spec } 32 get { theme.spec }
33 set { 33 set {
34 let new = MobileTheme(newValue) 34 let new = MobileTheme(newValue)
35 guard new.spec != theme.spec || new.font != theme.font else { return } 35 guard new.spec != theme.spec || new.font != theme.font || new.body != theme.body else { return }
36 theme = new 36 theme = new
37 paragraphStyles = [:] 37 paragraphStyles = [:]
38 applyThemeToView() 38 applyThemeToView()
Sources/OrgstarMobile/MobileTheme.swift +29 −5
@@ -7,7 +7,10 @@ import UIKit
7@MainActor 7@MainActor
8struct MobileTheme { 8struct MobileTheme {
9 let spec: ThemeSpec 9 let spec: ThemeSpec
10 /// The fixed-pitch font: columns, tables, code and the rest of `Presentation.isFixedPitch`.
10 let font: UIFont 11 let font: UIFont
12 /// The font for prose; `font` unless the theme names a body font.
13 let body: UIFont
11 14
12 init(_ spec: ThemeSpec = .default) { 15 init(_ spec: ThemeSpec = .default) {
13 self.spec = spec 16 self.spec = spec
@@ -16,7 +19,24 @@ struct MobileTheme {
16 // theme's size for the default Dynamic Type size, scaled for others. 19 // theme's size for the default Dynamic Type size, scaled for others.
17 let chosen = spec.font.isEmpty || UIFont.fontNames(forFamilyName: spec.font).isEmpty ? nil 20 let chosen = spec.font.isEmpty || UIFont.fontNames(forFamilyName: spec.font).isEmpty ? nil
18 : UIFont(descriptor: UIFontDescriptor(fontAttributes: [.family: spec.font]), size: size) 21 : UIFont(descriptor: UIFontDescriptor(fontAttributes: [.family: spec.font]), size: size)
19 font = UIFontMetrics(forTextStyle: .body).scaledFont(for: chosen ?? .monospacedSystemFont(ofSize: size, weight: .regular)) 22 let metrics = UIFontMetrics(forTextStyle: .body)
23 font = metrics.scaledFont(for: chosen ?? .monospacedSystemFont(ofSize: size, weight: .regular))
24 body = switch spec.bodyFont {
25 case "": font
26 case "system": metrics.scaledFont(for: .systemFont(ofSize: size))
27 case let family where !UIFont.fontNames(forFamilyName: family).isEmpty:
28 metrics.scaledFont(for: UIFont(descriptor: UIFontDescriptor(fontAttributes: [.family: family]), size: size))
29 default: font
30 }
31 }
32
33 /// Prose and fixed-pitch text use different fonts.
34 var mixedPitch: Bool { body != font }
35
36 /// The fixed-pitch font at the size and weight of `current`.
37 func fixedPitch(_ current: UIFont) -> UIFont {
38 let sized = font.withSize(current.pointSize)
39 return current.fontDescriptor.symbolicTraits.contains(.traitBold) ? Self.adding(.traitBold, to: sized) : sized
20 } 40 }
21 41
22 /// A color that follows the appearance, or nil when the theme has none for `key`. 42 /// A color that follows the appearance, or nil when the theme has none for `key`.
@@ -46,8 +66,8 @@ struct MobileTheme {
46 66
47 /// A heading's font: larger by the heading step for levels 1 to 3, bold. 67 /// A heading's font: larger by the heading step for levels 1 to 3, bold.
48 func headingFont(_ level: Int) -> UIFont { 68 func headingFont(_ level: Int) -> UIFont {
49 let size = font.pointSize + CGFloat(max(0, spec.headingSizeStep) * max(0, 4 - level)) 69 let size = body.pointSize + CGFloat(max(0, spec.headingSizeStep) * max(0, 4 - level))
50 return Self.adding(.traitBold, to: font.withSize(size)) 70 return Self.adding(.traitBold, to: body.withSize(size))
51 } 71 }
52 72
53 static func adding(_ traits: UIFontDescriptor.SymbolicTraits, to font: UIFont) -> UIFont { 73 static func adding(_ traits: UIFontDescriptor.SymbolicTraits, to font: UIFont) -> UIFont {
@@ -56,7 +76,7 @@ struct MobileTheme {
56 } 76 }
57 77
58 var base: [NSAttributedString.Key: Any] { 78 var base: [NSAttributedString.Key: Any] {
59 [.font: font, .foregroundColor: foreground, .paragraphStyle: paragraphStyle(firstLine: 0, wrapped: 0)] 79 [.font: body, .foregroundColor: foreground, .paragraphStyle: paragraphStyle(firstLine: 0, wrapped: 0)]
60 } 80 }
61 81
62 /// Markup hidden from view: no width, no color. 82 /// Markup hidden from view: no width, no color.
@@ -85,9 +105,13 @@ struct MobileTheme {
85 if let color = color(key) { storage.addAttribute(.foregroundColor, value: color, range: range) } 105 if let color = color(key) { storage.addAttribute(.foregroundColor, value: color, range: range) }
86 } 106 }
87 func traits(_ add: UIFontDescriptor.SymbolicTraits) { 107 func traits(_ add: UIFontDescriptor.SymbolicTraits) {
88 let current = storage.attribute(.font, at: range.location, effectiveRange: nil) as? UIFont ?? font 108 let current = storage.attribute(.font, at: range.location, effectiveRange: nil) as? UIFont ?? body
89 storage.addAttribute(.font, value: Self.adding(add, to: current), range: range) 109 storage.addAttribute(.font, value: Self.adding(add, to: current), range: range)
90 } 110 }
111 if mixedPitch, Presentation.isFixedPitch(role) {
112 let current = storage.attribute(.font, at: range.location, effectiveRange: nil) as? UIFont ?? body
113 storage.addAttribute(.font, value: fixedPitch(current), range: range)
114 }
91 switch role { 115 switch role {
92 case .heading(let level): 116 case .heading(let level):
93 storage.addAttribute(.font, value: headingFont(level), range: range) 117 storage.addAttribute(.font, value: headingFont(level), range: range)
Sources/OrgstarMobile/ReaderScreen.swift +2 −1
@@ -245,7 +245,8 @@ struct ReaderScreen: View {
245 var result = AttributedString() 245 var result = AttributedString()
246 for segment in segments { 246 for segment in segments {
247 var part = AttributedString(segment.text) 247 var part = AttributedString(segment.text)
248 var font = level.map(theme.headingFont) ?? theme.font 248 var font = level.map(theme.headingFont) ?? theme.body
249 if theme.mixedPitch, segment.roles.contains(where: Presentation.isFixedPitch) { font = theme.fixedPitch(font) }
249 var color = level.flatMap { theme.color("heading-\(min(max($0, 1), 8))") } ?? theme.foreground 250 var color = level.flatMap { theme.color("heading-\(min(max($0, 1), 8))") } ?? theme.foreground
250 func fg(_ key: String) { if let c = theme.color(key) { color = c } } 251 func fg(_ key: String) { if let c = theme.color(key) { color = c } }
251 // Outer roles first, so inner ones win. 252 // Outer roles first, so inner ones win.
Tests/OrgEditorAppKitTests/EditorTests.swift +26
@@ -244,6 +244,32 @@ struct EditingTests {
244 h.checkInSync() 244 h.checkInSync()
245 } 245 }
246 246
247 @Test func mixedPitch() throws {
248 let text = "**** Heading :tag:\nProse text.\n- item\n| a | b |\n#+begin_src sh\necho\n#+end_src\n"
249 let h = Harness(text)
250 var spec = ThemeSpec.default
251 spec.bodyFont = "system"
252 h.editor.themeSpec = spec
253 h.drainStyling()
254 let storage = try #require(h.textView.textStorage)
255 let ns = text as NSString
256 func fixed(_ needle: String, offset: Int = 0) -> Bool {
257 let font = storage.attribute(.font, at: ns.range(of: needle).location + offset, effectiveRange: nil) as? NSFont
258 return font?.isFixedPitch == true
259 }
260 #expect(!fixed("Prose"))
261 #expect(!fixed("Heading"))
262 #expect(fixed("****"))
263 #expect(fixed(":tag:"))
264 #expect(fixed("- item") && !fixed("item"))
265 #expect(fixed("| a"))
266 #expect(fixed("echo"))
267 // Body indentation is still counted in columns of the fixed-pitch font.
268 let style = try #require(storage.attribute(.paragraphStyle, at: ns.range(of: "Prose").location, effectiveRange: nil) as? NSParagraphStyle)
269 #expect(style.firstLineHeadIndent == 5 * h.editor.theme.column)
270 #expect(h.editor.theme.font.isFixedPitch)
271 }
272
247 @Test func styling() throws { 273 @Test func styling() throws {
248 let h = Harness("** b\nbody\n") 274 let h = Harness("** b\nbody\n")
249 let storage = try #require(h.textView.textStorage) 275 let storage = try #require(h.textView.textStorage)
Tests/OrgPresentationTests/MixedPitchTests.swift added +33
@@ -0,0 +1,33 @@
1import Foundation
2import OrgCore
3import Testing
4@testable import OrgPresentation
5
6struct MixedPitchTests {
7 @Test func fixedPitchRoles() {
8 for role: StyleRole in [.table, .rule, .block, .blockDelimiter, .verbatim, .code, .inlineSource, .metadata, .keyword, .tags, .timestamp, .syntax(.keyword)] {
9 #expect(Presentation.isFixedPitch(role), "\(role)")
10 }
11 for role: StyleRole in [.heading(level: 1), .bold, .italic, .link, .comment, .todo, .markup, .footnote] {
12 #expect(!Presentation.isFixedPitch(role), "\(role)")
13 }
14 }
15
16 @Test func prefixesThatSetIndentation() {
17 let text = "** Heading\nProse here.\n indented prose\n- item\n - [ ] box\n12. twelve\n\tTabbed\n*bold* not a heading\n" as NSString
18 let prefixes = Presentation.fixedPitchPrefixes(text, in: 0..<text.length).map { text.substring(with: NSRange($0)) }
19 #expect(prefixes == ["** ", " ", "- ", " - [ ] ", "12. ", "\t"])
20 }
21
22 @Test func prefixesOnlyInRange() {
23 let text = "- a\n- b\n" as NSString
24 #expect(Presentation.fixedPitchPrefixes(text, in: 4..<8) == [4..<6])
25 }
26
27 @Test func bodyFontInSpec() {
28 var spec = ThemeSpec.default
29 #expect(spec.bodyFont.isEmpty)
30 spec.bodyFont = "system"
31 #expect(spec != ThemeSpec.default)
32 }
33}
docs/manual/guide/02-the-editor.org +1 −1
@@ -30,7 +30,7 @@ The two Org options are in Settings ▸ Editing as "Emacs hides emphasis markers
30- Blocks (=#+BEGIN_…= to =#+END_…=), dynamic blocks and fixed-width lines are drawn on a shaded band across the whole width of the editor, as Emacs extends the =org-block= face. Code in src blocks is highlighted for its language (see [[file:11-code-blocks.org][Code blocks]]). 30- Blocks (=#+BEGIN_…= to =#+END_…=), dynamic blocks and fixed-width lines are drawn on a shaded band across the whole width of the editor, as Emacs extends the =org-block= face. Code in src blocks is highlighted for its language (see [[file:11-code-blocks.org][Code blocks]]).
31- A folded heading shows an ellipsis after its line. 31- A folded heading shows an ellipsis after its line.
32 32
33Colours come from the theme and follow the system's light or dark appearance. The font, size and line spacing are in Settings ▸ Appearance; colours are set in =config.toml=. See [[file:13-configuration.org][Configuration]]. Use a monospaced font: tags and tables line up by columns. 33Colours come from the theme and follow the system's light or dark appearance. The font, size and line spacing 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** Indentation and stars 35** Indentation and stars
36 36
docs/manual/guide/13-configuration.org +6 −3
@@ -103,6 +103,7 @@ orgstar's menus, settings and agenda are in English and German, and follow the l
103| Control | Range | Default | Key | 103| Control | Range | Default | Key |
104|---------------------------------+-----------------------------------------------+--------------------+---------------------| 104|---------------------------------+-----------------------------------------------+--------------------+---------------------|
105| Font | System monospaced, or any installed monospaced family | System monospaced | =font= | 105| Font | System monospaced, or any installed monospaced family | System monospaced | =font= |
106| Body text | Same as Font, System, or any installed proportional family | Same as Font | =body-font= |
106| Size | 8 to 36 pt | 13 pt | =font-size= | 107| Size | 8 to 36 pt | 13 pt | =font-size= |
107| Line spacing | 0 to 16 pt | 2 pt | =line-spacing= | 108| Line spacing | 0 to 16 pt | 2 pt | =line-spacing= |
108| Headings grow by N pt a level | 0 to 8 pt | 1 pt | =heading-size-step= | 109| Headings grow by N pt a level | 0 to 8 pt | 1 pt | =heading-size-step= |
@@ -359,6 +360,7 @@ Publishing projects, one table each, as =org-publish-project-alist= has them. Th
359| Key | Type | Default | Effect | 360| Key | Type | Default | Effect |
360|---------------------+---------+---------+----------------------------------------------------------------------------------------------| 361|---------------------+---------+---------+----------------------------------------------------------------------------------------------|
361| =font= | string | =""= | A font family. =""= uses the system's monospaced font. | 362| =font= | string | =""= | A font family. =""= uses the system's monospaced font. |
363| =body-font= | string | =""= | A font family for prose, or ="system"= for the system's proportional font. =""= uses =font= throughout. |
362| =font-size= | integer | =13= | Points. | 364| =font-size= | integer | =13= | Points. |
363| =line-spacing= | integer | =2= | Points between lines. | 365| =line-spacing= | integer | =2= | Points between lines. |
364| =heading-size-step= | integer | =1= | Points a heading is larger than the level below. Level 4 and deeper are body size. | 366| =heading-size-step= | integer | =1= | Points a heading is larger than the level below. Level 4 and deeper are body size. |
@@ -765,11 +767,12 @@ orgstar follows the system's light or dark appearance (System Settings ▸ Appea
765 767
766* Fonts 768* Fonts
767 769
768The editor uses one font for everything: body text, headings, code and tables. Choose it in Settings ▸ Appearance or with =font= under =[theme]=. 770By default the editor uses one font for everything: body text, headings, code and tables. Choose it in Settings ▸ Appearance or with =font= under =[theme]=.
769 771
770- The Font menu lists installed monospaced families. =config.toml= accepts any family name; a family that isn't installed falls back to the system's monospaced font. Tags and tables line up in columns, so a proportional font misaligns them. 772- The Font menu lists installed monospaced families. =config.toml= accepts any family name; a family that isn't installed falls back to the system's monospaced font. Tags and tables line up in columns, so a proportional font there misaligns them.
773- Body text (=body-font=) sets a second font for prose, as Emacs's =mixed-pitch-mode= does. Paragraphs, list text and headings use it. Tables, source and example blocks, verbatim and code, keyword lines, planning lines, drawers, timestamps and tags keep =font=, and so do a heading's stars and a line's leading blanks, bullet and checkbox, so text still starts under the indentation. Tags after a heading in the body font no longer line up at =org-tags-column=; the file is unchanged. A family that isn't installed falls back to =font=.
771- =font-size= is the body size, at least 6 points. 774- =font-size= is the body size, at least 6 points.
772- Headings are bold. Level 1 is =font-size= plus three times =heading-size-step=, level 2 plus two times, level 3 plus one time; level 4 and deeper are body size. Set =heading-size-step = 0= for one size throughout. 775- Headings are bold. Level 1 is =font-size= plus three times =heading-size-step=, level 2 plus two times, level 3 plus one time; level 4 and deeper are body size. Set =heading-size-step = 0= for one size throughout.
773- =line-spacing= adds space between lines, in points. 776- =line-spacing= adds space between lines, in points.
774 777
775On iPhone and iPad, the editor and reader use the same theme, read from the synced configuration folder. =font= applies when the family is installed on the device, otherwise the system's monospaced font is used, and =font-size= is the size at the default Dynamic Type setting, scaled with the size chosen on the device. The =selection= color, the =cursor= color and the =syntax-*= colors apply there too. See [[file:14-ios.org][iPhone and iPad]]. 778On iPhone and iPad, the editor and reader use the same theme, read from the synced configuration folder. =font= and =body-font= apply when the family is installed on the device, otherwise the system's monospaced font is used, and =font-size= is the size at the default Dynamic Type setting, scaled with the size chosen on the device. The =selection= color, the =cursor= color and the =syntax-*= colors apply there too. See [[file:14-ios.org][iPhone and iPad]].
docs/manual/guide/14-ios.org +1 −1
@@ -82,7 +82,7 @@ Files that aren't valid UTF-8 open read-only; commands that would change them sa
82 82
83The editor and the reader use the theme set in the configuration folder's =config.toml=, stacked as on the Mac: the default theme, then the theme file named by =theme-file=, then the colours in =[theme]=, =[theme.light]=, =[theme.dark]=, =[theme.todo]= and =[theme.category]=. A TODO keyword without a colour in =[theme.todo]= takes its class's colour: =todo-next= for =NEXT= and =STRT=, =todo-waiting= for =WAIT= and =HOLD=, =todo-cancelled= for =KILL= and =CANCELLED=, and so on (see [[file:13-configuration.org][Configuration]] for the lists). Colours follow the system's light or dark appearance. Problems in the theme show in the Settings tab with the other problems. A change to =config.toml= or the theme file applies as it syncs, to open editors too. See [[file:13-configuration.org][Configuration]] for the colour keys. 83The editor and the reader use the theme set in the configuration folder's =config.toml=, stacked as on the Mac: the default theme, then the theme file named by =theme-file=, then the colours in =[theme]=, =[theme.light]=, =[theme.dark]=, =[theme.todo]= and =[theme.category]=. A TODO keyword without a colour in =[theme.todo]= takes its class's colour: =todo-next= for =NEXT= and =STRT=, =todo-waiting= for =WAIT= and =HOLD=, =todo-cancelled= for =KILL= and =CANCELLED=, and so on (see [[file:13-configuration.org][Configuration]] for the lists). Colours follow the system's light or dark appearance. Problems in the theme show in the Settings tab with the other problems. A change to =config.toml= or the theme file applies as it syncs, to open editors too. See [[file:13-configuration.org][Configuration]] for the colour keys.
84 84
85- Font :: =font= when that family is installed on the device, otherwise the system's monospaced font. 85- Font :: =font= when that family is installed on the device, otherwise the system's monospaced font. =body-font=, when set, is used for prose as on the Mac.
86- Size :: =font-size= is the size at the default Dynamic Type setting, 13 pt by default. Text grows and shrinks with the text size chosen in the system Settings app. 86- Size :: =font-size= is the size at the default Dynamic Type setting, 13 pt by default. Text grows and shrinks with the text size chosen in the system Settings app.
87- Line spacing and headings :: =line-spacing= and =heading-size-step= apply as on the Mac. 87- Line spacing and headings :: =line-spacing= and =heading-size-step= apply as on the Mac.
88- Caret and selection :: the selection highlight takes the theme's =selection= colour, over block bands too; the caret and the selection handles take =cursor=. 88- Caret and selection :: the selection highlight takes the theme's =selection= colour, over block bands too; the caret and the selection handles take =cursor=.