Skip to content

Instantly share code, notes, and snippets.

@anzfactory
Last active January 22, 2021 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anzfactory/c77f386ff5d221e95df0e93b44bdde41 to your computer and use it in GitHub Desktop.
Save anzfactory/c77f386ff5d221e95df0e93b44bdde41 to your computer and use it in GitHub Desktop.
DeepLを開くXcode Source Editor Extension
import AppKit
import Foundation
import XcodeKit
final class SourceEditorCommand: NSObject, XCSourceEditorCommand {
func perform(with invocation: XCSourceEditorCommandInvocation, completionHandler: @escaping (Error?) -> Void ) -> Void {
defer {
completionHandler(nil)
}
guard
let lines = invocation.buffer.lines as? [String],
let selectionRanges = invocation.buffer.selections as? [XCSourceTextRange]
else {
return
}
let text = selectionRanges.map { (range) -> String in
return (range.start.line ... range.end.line).map { row -> String in
let line = lines[row] // 選択している行のテキストすべて
let startColumn = row == range.start.line ? range.start.column : 0
let endColumn = row == range.end.line ? range.end.column : line.count - 1
let startIndex = line.index(line.startIndex, offsetBy: startColumn)
let endIndex = line.index(line.startIndex, offsetBy: endColumn)
return String(line[startIndex ..< endIndex]).trimmingCharacters(in: .whitespaces) // 選択範囲内の文字列を抽出
}.joined(separator: " ")
}.joined(separator: "\n")
guard !text.isEmpty else {
return
}
NSWorkspace.shared.open(.translationURL(text: text))
}
}
extension URL {
static let deepL: URL = URL(string: "https://www.deepl.com/")!
static func translationURL(text: String) -> URL {
guard let textEncoded = text.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
return .deepL
}
return URL(string: "ja/translator#en/ja/\(textEncoded)", relativeTo: .deepL)!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment