Created
January 15, 2025 20:18
-
-
Save monkeydom/84dcbc3b967ec571dc1c5e2e50da519e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env swift | |
import Cocoa | |
let args = CommandLine.arguments | |
var argi = 1 | |
var fontname = "Iosevka" | |
var fontsize = CGFloat(40.0) | |
while argi < args.count { | |
let arg = args[argi] | |
if arg == "-f" { | |
fontname = args[argi+1] | |
argi += 1 | |
} else if arg == "-s" { | |
fontsize = CGFloat(Float(args[argi+1]) ?? 40.0) | |
argi += 1 | |
} else if arg == "-h" { | |
print("\(args[0]) [-f <fontname>] [-s <fontsize>]") | |
print("If there is HTML on the pasteboard, cleans it a bit, and puts it back on as RTF for e.g. Keynote") | |
exit(1) | |
} | |
argi += 1 | |
} | |
let type = NSPasteboard.PasteboardType.html | |
if let string = NSPasteboard.general.string(forType: type) { | |
separate("Input") | |
print(string) | |
separate("Output") | |
let output = processed(string) | |
print(output) | |
let data = Data(output.utf8) | |
if let attributedString = try? NSMutableAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) { | |
let fullRange = NSRange(location: 0, length: attributedString.length) | |
let font = NSFont(name: fontname, size: fontsize) ?? NSFont(name: "Iosevka", size: fontsize) | |
attributedString.addAttribute(NSAttributedString.Key.font, value: font as Any, range: fullRange) | |
let gp = NSPasteboard.general | |
gp.prepareForNewContents() | |
gp.writeObjects([attributedString]) | |
gp.setString(output, forType: type) | |
} | |
} else { | |
print("No html on pasteboard") | |
exit(1) | |
} | |
func processed(_ input: String) -> String { | |
let bc = #/background-color: #[\da-f]+;/# | |
var result = input.replacing(bc) { _match in "" } | |
let font = #/font-family: [^;]+;/# | |
result = result.replacing(font) {_match in "font-family: '\(fontname)';"} | |
let fontsize = #/font-size: [^;]+;/# | |
result = result.replacing(fontsize) {_match in "font-size: \(fontsize)pt;"} | |
result = result.replacing(#/line-height: [^;]+;/#) {_match in ""} | |
return result | |
} | |
func separate(_ t: String) { | |
print("\(t):") | |
print("".padding(toLength: t.count + 1, withPad:"=-", startingAt:0)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment