Sources/OrgCore/Semantic/DisplayWidth.swift

974c897ecb48b138c67b0c0e8115887978db2b89
orgstar/Sources/OrgCore/Semantic/DisplayWidth.swift

20 lines · 885 bytes

 1/// Columns a string occupies in a monospaced table: East Asian wide and fullwidth characters
 2/// and emoji take two, everything else one. Combining marks belong to their Character.
 3public func displayWidth(_ text: some StringProtocol) -> Int {
 4    text.reduce(0) { $0 + displayWidth(of: $1) }
 5}
 6
 7func displayWidth(of character: Character) -> Int {
 8    guard let scalar = character.unicodeScalars.first else { return 0 }
 9    if scalar.properties.isEmojiPresentation { return 2 }
10    switch scalar.value {
11    case 0x00...0x08, 0x0B...0x1F, 0x7F:
12        // Emacs shows a control character as `^M`.
13        return character.unicodeScalars.count == 1 ? 2 : 1
14    case 0x1100...0x115F, 0x2E80...0x303E, 0x3041...0xA4CF, 0xAC00...0xD7A3, 0xF900...0xFAFF,
15         0xFE30...0xFE4F, 0xFF00...0xFF60, 0xFFE0...0xFFE6, 0x20000...0x3FFFD:
16        return 2
17    default:
18        return 1
19    }
20}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form