Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,14 @@ In UIKit, set `isSelectable` on `TranscriptTextView`.
On devices that have Writing Tools, the edit menu can offer them for the selected text, as in a `UITextView`. Turn
them off with `.showsWritingTools(false)`, or with `showsWritingTools` on `TranscriptTextView`.

Copy puts two forms of the selected text on the pasteboard. The plain text is readable as Markdown, with list
markers, quote prefixes and tables (see `copyText(in:)` on `TranscriptDocument`). The rich text is RTF, with the
fonts of the text, bold, italic, code, links, strikethrough and underline. The system font has a private name that
some apps do not find, so the RTF names Helvetica Neue in its place, with the same size, bold and italic. It has no
colors, so pasted text takes the colors of the place it goes to. Its list markers, quote prefixes, tables and rules are
the characters of the plain text, not RTF lists or tables. Text in a table cell keeps its bold, italic, code and
links. An app that reads plain text gets the plain text.

### VoiceOver

VoiceOver reads the text block by block. Headings are in the rotor's list of headings, list items start with their
Expand Down
96 changes: 96 additions & 0 deletions Sources/TranscriptKit/Model/RichCopy.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import Foundation
import UniformTypeIdentifiers
#if canImport(UIKit)
import UIKit
#elseif canImport(AppKit)
import AppKit
#endif

extension TranscriptDocument {
/// What copying `range` puts on the pasteboard, as one item by type
/// identifier: the plain text of `copyText(in:)`, and the same text as
/// RTF, with the fonts of `style`, links, strikethrough and underline.
/// The RTF has no colors, so pasted text takes the colors of the place
/// it goes to. The system font becomes Helvetica Neue, with the same
/// size, bold and italic.
func pasteboardItem(in range: Range<Int>, style: TranscriptStyle) -> [String: Any] {
let text = Self.withPublicFonts(copiedText(in: range, style: style))
var item: [String: Any] = [UTType.utf8PlainText.identifier: text.string]
if let rtf = try? text.data(from: NSRange(location: 0, length: text.length),
documentAttributes: [.documentType: NSAttributedString.DocumentType.rtf]) {
item[UTType.rtf.identifier] = rtf
}
return item
}

/// `text` with each font that has a private name (the system fonts,
/// whose names start with a period) changed to a public font of the
/// same size and traits. Apps that find a font by its name in the RTF
/// can fail to find a private name, and show another font.
static func withPublicFonts(_ text: NSAttributedString) -> NSAttributedString {
let result = NSMutableAttributedString(attributedString: text)
let whole = NSRange(location: 0, length: result.length)
text.enumerateAttribute(TranscriptStyle.fontKey, in: whole) { value, range, _ in
guard let value else { return }
let font = value as! CTFont
let name = CTFontCopyPostScriptName(font) as String
guard name.hasPrefix(".") else { return }
result.addAttribute(TranscriptStyle.fontKey, value: publicFont(like: font), range: range)
}
return result
}

private static func publicFont(like font: CTFont) -> CTFont {
let traits = CTFontGetSymbolicTraits(font)
let size = CTFontGetSize(font)
let name = traits.contains(.traitMonoSpace) ? "Menlo-Regular" : "HelveticaNeue"
let base = CTFontCreateWithName(name as CFString, size, nil)
let wanted = traits.intersection([.traitBold, .traitItalic])
guard !wanted.isEmpty else { return base }
return CTFontCreateCopyWithSymbolicTraits(base, 0, nil, wanted, wanted) ?? base
}

/// Styles the spans of `block` in `piece`, which holds the block's text
/// from UTF-16 offset `start` on: the fonts of bold, italic and code, and
/// links, strikethrough and underline, with the attributes that other
/// apps read.
func styleSpans(of block: TranscriptBlock, from start: Int, in piece: NSMutableAttributedString, style: TranscriptStyle) {
let length = piece.length
let spans = block.spans.compactMap { span -> InlineSpan? in
let lower = min(max(span.range.lowerBound - start, 0), length)
let upper = min(max(span.range.upperBound - start, 0), length)
guard lower < upper else { return nil }
var shifted = span
shifted.range = lower..<upper
return shifted
}
guard !spans.isEmpty else { return }
var cuts: Set<Int> = [0, length]
for span in spans {
cuts.insert(span.range.lowerBound)
cuts.insert(span.range.upperBound)
}
let sorted = cuts.sorted()
for (lower, upper) in zip(sorted, sorted.dropFirst()) {
var traits: InlineSpan.Traits = []
var link: String?
for span in spans where span.range.lowerBound <= lower && span.range.upperBound >= upper {
traits.formUnion(span.traits)
if let destination = destination(of: span) { link = destination }
}
let range = NSRange(location: lower, length: upper - lower)
if !traits.intersection([.bold, .italic, .code]).isEmpty {
piece.addAttribute(TranscriptStyle.fontKey, value: style.font(for: block.kind, traits: traits), range: range)
}
if traits.contains(.strikethrough) {
piece.addAttribute(.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: range)
}
if traits.contains(.underline) {
piece.addAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: range)
}
if let link, let url = URL(string: link) {
piece.addAttribute(.link, value: url, range: range)
}
}
}
}
69 changes: 50 additions & 19 deletions Sources/TranscriptKit/Model/TranscriptDocument.swift
Original file line number Diff line number Diff line change
Expand Up @@ -420,7 +420,15 @@ public struct TranscriptDocument: Equatable, Sendable {
/// Markdown tables and images as their alt text, with a blank line
/// between blocks that are not neighbouring list content.
public func copyText(in range: Range<Int>) -> String {
var result = ""
copiedText(in: range, style: nil).string
}

/// The text of `copyText(in:)`, with the fonts of `style`, links,
/// strikethrough and underline when `style` is set, and no attributes
/// otherwise.
func copiedText(in range: Range<Int>, style: TranscriptStyle?) -> NSAttributedString {
let result = NSMutableAttributedString()
let separatorAttributes = style.map { [TranscriptStyle.fontKey: $0.font(for: .paragraph)] } ?? [:]
var previousWasInList = false
var start = 0
for block in blocks {
Expand All @@ -431,25 +439,26 @@ public struct TranscriptDocument: Equatable, Sendable {
let lower = max(range.lowerBound, start)
let upper = min(range.upperBound, start + length)
let includesStart = range.lowerBound <= start && range.upperBound > start
var piece: String
let attributes = style.map { [TranscriptStyle.fontKey: $0.font(for: block.kind)] } ?? [:]
var piece: NSMutableAttributedString
switch block.kind {
case .rule:
guard includesStart else { continue }
piece = "---"
piece = NSMutableAttributedString(string: "---", attributes: attributes)
case .table(let table):
guard lower < upper || includesStart else { continue }
piece = Self.markdownTable(table, text: block.text, local: (lower - start)..<(upper - start))
piece = markdownTable(table, of: block, local: (lower - start)..<(upper - start), attributes: attributes, style: style)
case .paragraph, .heading, .code:
guard lower < upper else { continue }
let local = NSRange(location: lower - start, length: upper - lower)
let text = NSMutableString(string: (block.text as NSString).substring(with: local))
piece = NSMutableAttributedString(string: (block.text as NSString).substring(with: local), attributes: attributes)
if let style { styleSpans(of: block, from: local.location, in: piece, style: style) }
// Images by their alt text and formulas by their LaTeX, last
// first so offsets stay valid.
for span in block.spans.reversed() where local.contains(span.range.lowerBound) {
guard let replacement = span.image?.alt ?? span.math?.source else { continue }
text.replaceCharacters(in: NSRange(location: span.range.lowerBound - local.location, length: 1), with: replacement)
piece.replaceCharacters(in: NSRange(location: span.range.lowerBound - local.location, length: 1), with: replacement)
}
piece = text as String
}

// Container prefixes: the first line gets the list marker, later
Expand Down Expand Up @@ -481,27 +490,49 @@ public struct TranscriptDocument: Equatable, Sendable {
// A selection that starts inside the block starts mid-line.
if !includesStart { firstPrefix = "" }
if !firstPrefix.isEmpty || !restPrefix.isEmpty {
let lines = piece.components(separatedBy: "\n")
piece = lines.enumerated().map { ($0.offset == 0 ? firstPrefix : restPrefix) + $0.element }.joined(separator: "\n")
let prefixed = NSMutableAttributedString()
var lineStart = 0
func appendLine(upTo end: Int) {
let prefix = lineStart == 0 ? firstPrefix : restPrefix
if !prefix.isEmpty { prefixed.append(NSAttributedString(string: prefix, attributes: attributes)) }
prefixed.append(piece.attributedSubstring(from: NSRange(location: lineStart, length: end - lineStart)))
lineStart = end
}
for (offset, unit) in piece.string.utf16.enumerated() where unit == 0x0A { appendLine(upTo: offset + 1) }
appendLine(upTo: piece.length)
piece = prefixed
}

let isInList = block.listLevel > 0
if !result.isEmpty { result += previousWasInList && isInList ? "\n" : "\n\n" }
result += piece
if result.length > 0 {
result.append(NSAttributedString(string: previousWasInList && isInList ? "\n" : "\n\n", attributes: separatorAttributes))
}
result.append(piece)
previousWasInList = isInList
}
return result
}

/// The rows of `table` that `local` touches, as a Markdown table.
private static func markdownTable(_ table: TranscriptTable, text: String, local: Range<Int>) -> String {
let string = text as NSString
var lines: [String] = []
/// The rows of `table` that `local` touches, as a Markdown table. With
/// `style`, each cell keeps the styles of its spans.
private func markdownTable(_ table: TranscriptTable, of block: TranscriptBlock, local: Range<Int>,
attributes: [NSAttributedString.Key: Any], style: TranscriptStyle?) -> NSMutableAttributedString {
let string = block.text as NSString
let result = NSMutableAttributedString()
func append(_ text: String) { result.append(NSAttributedString(string: text, attributes: attributes)) }
for (index, row) in table.rows.enumerated() {
guard let first = row.first, let last = row.last,
first.lowerBound < max(local.upperBound, local.lowerBound + 1), last.upperBound >= local.lowerBound else { continue }
let cells = row.map { string.substring(with: NSRange(location: $0.lowerBound, length: $0.count)) }
lines.append("| " + cells.joined(separator: " | ") + " |")
if result.length > 0 { append("\n") }
append("| ")
for (column, cell) in row.enumerated() {
if column > 0 { append(" | ") }
let range = NSRange(location: cell.lowerBound, length: cell.count)
let piece = NSMutableAttributedString(string: string.substring(with: range), attributes: attributes)
if let style { styleSpans(of: block, from: cell.lowerBound, in: piece, style: style) }
result.append(piece)
}
append(" |")
if index == 0 {
let rule = table.alignments.map { alignment -> String in
switch alignment {
Expand All @@ -510,9 +541,9 @@ public struct TranscriptDocument: Equatable, Sendable {
case .trailing: return "---:"
}
}
lines.append("| " + rule.joined(separator: " | ") + " |")
append("\n| " + rule.joined(separator: " | ") + " |")
}
}
return lines.joined(separator: "\n")
return result
}
}
7 changes: 6 additions & 1 deletion Sources/TranscriptKit/iOS/TranscriptTextView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1800,6 +1800,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD
/// the view resign, and the selection must stay for them.
@discardableResult
public override func becomeFirstResponder() -> Bool {
addTextInteractionIfNeeded()
let became = super.becomeFirstResponder()
if became { NotificationCenter.default.post(name: Self.didBecomeFirstResponder, object: self) }
return became
Expand Down Expand Up @@ -1860,10 +1861,14 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD
}
}

/// Puts the selected text on the pasteboard as plain text, readable as
/// Markdown (see `TranscriptDocument.copyText(in:)`), and as rich text
/// with the fonts, links, strikethrough and underline of the text. In the
/// rich text, Helvetica Neue takes the place of the system font.
nonisolated public override func copy(_ sender: Any?) {
onMainThread {
guard let range = selectedRange else { return }
UIPasteboard.general.string = shownDocument.copyText(in: range)
UIPasteboard.general.setItems([shownDocument.pasteboardItem(in: range, style: currentLayout.style)])
}
}

Expand Down
16 changes: 16 additions & 0 deletions Tests/TranscriptKitTests/MarkdownTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,22 @@ func displayedTextOnlyGrowsWhileStreaming(newlinesAsLineBreaks: Bool) {
#expect(document.copyText(in: 0..<5) == "Intro")
}

@Test func copyTextPrefixesEveryLineOfABlock() {
let document = MarkdownStreamParser.document(from: "> quoted\n> ```\n> a\n> b\n> ```\n\n- item\n\n ```\n x\n y\n ```\n- last\n")
#expect(document.copyText(in: 0..<document.utf16Count) == """
> quoted

> a
> b

- item
x
y
- last
""")
#expect(document.copyText(in: 3..<document.utf16Count).hasPrefix("ted\n\n> a\n> b"))
}

@Test func linkHitTestingFindsOnlyTheLinkGlyphs() {
let document = MarkdownStreamParser.document(from: "Go to [the site](https://example.com) now")
let layout = DocumentLayout(document: document, width: 400)
Expand Down
Loading
Loading